Is it because of string pooling by CLR or by the GetHashCode() method of both strings return same value?
string s1 = "xyz";
string s2 = "xyz";
Console.WriteLine(" s1 reference equals s2 : {0}", object.ReferenceEquals(s1, s2));
Console writes : “s1 reference equals s2 : True”
I believe that, it’s not because of the GetHashCode() returns same value for both string instance. Because, I tested with custom object and overridden the GetHasCode() method to return a single constant every time. The two separate instances of this object does not equal in the reference.
Please let me know, what is happening behind the scene.
thanks
123Developer
It sounds like string interning – a method of storing only one copy of a string. It requires strings to be an immutable type in the language you are dealing with, and .Net satisfies that and uses string interning.
In string interning a string “xyz” is stored in the intern pool, and whenever you say “xyz” internally it references the entry in the pool. This can save space by only storing the string once. So a comparison of “xyz” == “xyz” will get interpreted as [pointer to 34576] == [pointer to 34576] which is true.