I was trying to better understand string's interning in c# and got into the following situation:
string a ="Hello";
string b ="Hello";
string c = new string(new char[]{'H','e','l','l','o'});
string d = String.Intern(c);
Console.WriteLine(a==b);
Console.WriteLine(c==d);
Console.WriteLine((object)a==(object)b);
Console.WriteLine((object)c==(object)d);
I'm getting the following result in console:
True
True
True
False
The mistake for me is that why is the 4th false ?
If you had not created a
(and b
), then Console.WriteLine((object)c==(object)d);
would have resulted in True
.
However, at the time that you do string d = String.Intern(c);
the string "Hello"
already exists in the string intern pool, due to a
, so the call to intern c
finds the already existing "Hello"
and returns it.
So, if "Hello"
had not already been interned, then the "Hello"
of c
would have been interned, in which case the returned d
would have been equal to c
.
Proof: if you do Console.WriteLine(b==d); it should return
True`. (I bet it will.)
The documentation says that the method return
The system's reference to str, if it is interned; otherwise, a new reference to a string with the value of str.
and in the remarks:
if you assign the same literal string to several variables, the runtime retrieves the same reference to the literal string from the intern pool and assigns it to each variable.
Apparently creating the string "Hello"
out of a char array results not in the same literal string, and it seems not to end up in the pool. changing the c-line to string c = "Hello"
results in the output of True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With