Mono Class Library: System.String Overview | Members

System.String.Intern Method

Retrieves the system's reference to a specified string. [Edit]

public static string Intern (string str)

Parameters

str
A string. [Edit]

Returns

The string reference to str. [Edit]

Exceptions

TypeReason
ArgumentNullExceptionstr is a null reference. [Edit]

Remarks

Instances of each unique literal string constant declared in a program, as well as any unique instance of string you add programmatically are kept in a table, called the "intern pool".

The intern pool conserves string storage. If a literal string constant is assigned 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 a specified string in the intern pool. If the string exists, a reference to it is returned. If it does not exist, an instance equal to the specified string is added to the intern pool and a reference that instance is returned.

[Edit]

Example

The following example demonstrates the string.Intern(string) method.

C# Example
using System;
using System.Text;
public class StringExample {
 public static void Main() {

     String s1 = "MyTest"; 
        String s2 = new StringBuilder().Append("My").Append("Test").ToString(); 
        String s3 = String.Intern(s2);

        Console.WriteLine(Object.ReferenceEquals(s1, s2));    //different
        Console.WriteLine(Object.ReferenceEquals(s1, s3));    //the same
    }
}

The output is

False
True

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0