Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

False after casting interned strings to objects [duplicate]

Tags:

string

c#

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 ?

like image 403
Samvel Petrosov Avatar asked Jul 13 '17 07:07

Samvel Petrosov


2 Answers

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 returnTrue`. (I bet it will.)

like image 172
Mike Nakis Avatar answered Oct 24 '22 19:10

Mike Nakis


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

like image 23
Mong Zhu Avatar answered Oct 24 '22 20:10

Mong Zhu