System Namespace String Class
Retrieves the system's reference to the specified String.
[ VB ]
<Serializable>
Public Shared Function Intern ( _
ByVal str As String _
) As String
[ C# ]
[ Serializable ]
public static string Intern (
string str
);
[ C++ ]
[ Serializable ]
public: static String* Intern (
String* str
);
[ JScript ]
public Serializable
static function Intern (
str : String
) : String;
- str
- A String, or a null reference ( Nothing in Visual Basic ).
The String reference to str.
The common language runtime automatically maintains a table, called the "intern pool", which contains a single instance of each unique literal string constant declared in a program, as well as any unique instance of String you add programmatically.
The intern pool conserves string storage. If you assign a literal string constant to several variables, each variable is set to reference the same constant in the intern pool instead of referencing several different instances of String that have identical values.
This method looks up str in the intern pool. If str exists, a reference to it is returned. If str does not exist, an instance equal to str is added to the intern pool and a reference that instance is returned.
The code below generates a new String, "MyTest", using the StringBuilder class, and puts it into the intern pool. The string, s1, has already been interned because it is a literal in our program. The string, s2, has the same value, but is a different object than the one referenced by s3.
String s1 =
"MyTest";
String s2 =
new StringBuilder ( ).Append ( "My" ).Append ( "Test" ).ToString ( );
String s3 =
String.Intern ( s2 );
Response.WriteLine ( ( Object ) s2== ( Object ) s1 ); // Different
references.
Response.WriteLine ( ( Object ) s3== ( Object ) s2 ); // The same reference.
Compare this method to the IsInterned method.
String Members IsInterned