Retrieves the reference for the string.
[Visual Basic] Public Shared Function Intern( _ ByVal str As String _ ) As String [C#] public static string Intern( string str ); [C++] public: static String* Intern( String* str ); [JScript] public static function Intern( str : String ) : String;
The reference to the string.
Exception Type | Condition |
---|---|
ArgumentNullException | If the string is null. |
The Intern method looks up the string in a table of string identities of AppDomain. It is used primarily for constants and returns a reference to the "official" copy of the string.
All literal strings in the program are automatically interned. The only strings that need to be interned are those that are passed by arguments or generated by the code. String interning is useful when you are creating strings on the fly.
The code below generates a one new String ("FooBar"), using the StringBuilder, and is put into the string intern pool. The string "FooBar" has already been interned because it is a literal in our program, so a reference to it returned from the String.Itern method. The string that is passed to String.Intern (s2) has the same value, but is a different object than the one that is returned (s3).
String s2 = new StringBuilder().Append("Foo").Append("Bar").ToString();
String s3 =String.Intern(s2);
String s = "FooBar";
Console.WriteLine((Object)s2==(Object)s);//Should be different.
Console.WriteLine((Object)s3==(Object)s);//Should be the same; the appropriate value is pulled from the String interning pool.
Note that the C# compiler will concatenate the first two strings while compiling so there is no need to do any explicit string interning.
The other relevant method is IsInterned. This takes a string as an argument. If that string has already been interned, it returns a reference to the interned object; otherwise it returns null.
Note that if the string is null, it will cause an exception to be thrown.