C# Crawler
Sagiv Hadaya is crawling in C#...just for fun




 

String Interned

Defenition: The CLR maintains a table (the "intern pool"), which holds one instance of each unique string declared in a program, as well as any unique instance of string you programmatically added.

That means that if you assign a string constant to more than one variable, each variable is set to reference the same constant in the intern pool instead of referencing several different instances.

take a look at this block of code:

 

string str1="I Love You";

string str2="I Love";

str2 = str2.Insert (str2.Length," You");

Console.WriteLine((object)str1==(object)str2);

 

The last line compares the two object references, this block will generate FALSE, and that is because at first "I Love You" and "I Love" are two different strings, meaning they reference different object in the intern pool, even after we add " You" to str2 still nothing refreshes the intern pool for that string object. to fixt that we will use string.Intern method as such:

 

string str1="I Love You";

string str2="I Love";

str2 = str2.Insert (str2.Length," You");

str2 = string.Intern (str2);

Console.WriteLine((object)str1==(object)str2);

 

this line of code will generate TRUE, the 5th line of code, checks the string literal upon the intern pool, if found, str2 will reference the object in the intern pool, and the object it just referenced to will ge garbaged collected.


Click here to visit the Radio UserLand website.
Click to see the XML version of this web page.
Click here to send an email to the editor of this weblog.
© Copyright 2002 Sagiv Hadaya.
Last update: 10/11/2002; 1:54:06 AM.