Code Block
string c = "Hello", d = "Hello";
Console.WriteLine("c is of Type : {0}, d is of Type : {1} ", c.GetType(),d.GetType());
Console.WriteLine("c==d {0}", object.ReferenceEquals(c, d));
Console.WriteLine("c and d hashCode are equal {0}",
c.GetHashCode() == d.GetHashCode());
Output
c is of Type : System.String, d is of Type : System.String
c==d True
c and d hashCode are equal True
Code Block
string e = "Hello", f = "Hello";
e += " world";
f += " world";
Console.WriteLine("e is of Type : {0}, f is of Type : {1} ", c.GetType(),d.GetType());
Console.WriteLine("e==f {0}", object.ReferenceEquals(e, f));
Console.WriteLine("e and d hashCode are equal {0}", e.GetHashCode() == f.GetHashCode());
Output
e is of Type : System.String, f is of Type : System.String
e==f False
e and f hashCode are equal True
Question
Two different “strings” are the same object instance?
it is mentioned the Compiler is optimized that it will automatically reference to same string, which is relevant for variable c and d.
but in the case of variable e and f it should have pointed to the same string because e and f are re-assigned with new reference when we try to do += operation on string (stings are immutable),
but as per Answer in above link the variable f should have been assigned to the reference of e, but according to output these two variables were assigned new reference. Why so?