C#: String interning

Code Snippet: String Interning
Recall that the equivalence operator (==) will test for value equivalence for value types and for address or reference equivalence for reference types.
 
string a = "Hello";     // ldstr
string b = "Hello";     // ldstr (Interning)
string c = String.Copy(a);
Console.WriteLine(a == c);
Console.WriteLine((object)a == (object)c);
Console.WriteLine(a == b);                             // Call the op_Equality method
Console.WriteLine((object)a == (object)b);   
// opcode ceq (compare equal)
 
=== Program Output ===
True
False
True
True
 
The system is internaling strings—CLI guarantees that the result of two ldstr instructions refering to two metadata tokens with the same sequence of characters return precisely the same string object.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s