Misunderstanding inside string literals?

I do not understand:

MSDN says

http://msdn.microsoft.com/en-us/library/system.string.intern.aspx

Therefore, an instance of a literal string with a specific value exists only once in the system.

For example, if you assign the same literal string to multiple variables, the runtime returns the same reference to the string literal from the internal pool and assigns it to each variable.

Is this the default behavior (without intern)? or using the intern method?

  • If its the default, then why do I want to use an intern? (the instance will be once already ...)?

  • If its NOT the default: if I write 1000 times of this line:

    Console.WriteLine ("Lalala");

1), will I get 1000 entries of "lalala" in memory? (without using an intern ...)

2) will "lalala" eventually be Gc'ed?

3) Is Lalala already interned? and if so, why do I need to β€œget” it from the pool and not just write β€œlalala” again?

A bit confusing.

+5
source share
2 answers

String literals get interned automatically (so if your code contains "lalala" 1000 times, there will only be one instance).

Such strings will not receive GC'd, and at any time when they are referenced, the link will be interned.


string.Intern , - , , , , , .

+9

- , , , , . - . : , , , . (, 99,999% , 0,001 - .)

, , , "lalala" - - . , "lalala" , , , , .

, , ( .exe), , , .


EDIT

, , Equals(). Equals() String , , ; , true; , , false, , . , . ( , , - , .)

, , s, switch :

switch( s )
{
    case "cat": ....
    case "dog": ....
    case "tod": ....
}

"cat", "dog", "tod" , s, , . s switch, , switch, .

, , , , , , .

+5

All Articles