An addition to the provided answer:
string (C# Reference)
The System.String class is an immutable reference type provided in
the .NET framework class library. This class creates a new string
object internally for any string manipulation action. The contents of
objects of this type do not change, although the syntax makes it
appear as if contents can be changed. In addition, string is used as
hash table key for the computation of hash values to avoid the risk of
corrupting the hash data structure.
Example:
string a = "hello";
string b = "h";
// Append to contents of 'b'
b += "ello";
// When you set the variable's b value to "hello",
// this would result in changing the pointer
// to the object in the HEAP the variable "a" is already pointing to
// Result would be: (reference of a == reference of b) --> TRUE
// b = "hello";
Console.WriteLine(a == b); // value comparison
Console.WriteLine((object)a == (object)b); // reference comparison
Console.WriteLine (object.ReferenceEquals(a,b)); // reference comparison without casting
Result:
True
False
False
Explanation:
This will create a new object:
string a = "hello";
This will create another object:
string b = "h";
This will create yet another object:
b += "ello";
The following will create a reference to an existing object, more precisely, it will point to the same object the variable "a" points to → "hello".
string c = "hello";
Console.WriteLine (object.ReferenceEquals(a,c)); // --> TRUE
Strings are immutable--the contents of a string object cannot be
changed after the object is created, although the syntax makes it
appear as if you can do this. For example, when you write this code,
the compiler actually creates a new string object to hold the new
sequence of characters, and that new object is assigned to b. The
string "h" is then eligible for garbage collection.
operator==(object, object)
(reference equality) instead of the (better fit, as far as overload resolution is concerned)operator==(string, string)
(value equality), hence the cast. Operator calls are not polymorphic, they are resolved at compile time. An alternative would be to callobject.ReferenceEquals()
without the casting. – Elfstring e = c + c;
thene
anda
would NOT compare equal using the "object" version, but would compare equal by just using == with no cast. That's the key point to understanding string interning: that it changes reference comparisons while keeping value comparisons the same. – Guppy