I already knew that in C#, string are reference type that are handled mostly like a value type, but I recently discover this: http://net-informations.com/faq/general/immutable.htm
I'm trying to "prove" that string are immutable by printing the reference to a string variable anytime a concatenation occurs:
string s = string.Empty;
for (int i = 0; i < 10; i++)
{
s += " " + i;
// Console.WriteLine(&s);
}
As you can guess, the code doesn't compile if the line is uncommented (Compiler Error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('type')).
I also tried the GetHashCode(), but apparently for string it returns the same value based on the... String value itself (ie. it will always return the same result for "0" for instance).
Is there a way to do that? It won't be for a coding purpose, just for an understanding purpose... If not, how can you know that it will "really" create n instances of a string at each concatenation? Appart from "knowing it"...
EDIT: probably not a duplicate of C# memory address and variable, because I want to know how to get the address of a reference type, and apparently that thread deals only with value type.
If you want to check that a new instance was created, just compare it to the previous instance:
string s = string.Empty;
for (int i = 0; i < 10; i++)
{
var saved = s;
s += " " + i;
if (ReferenceEquals(saved, s))
Console.WriteLine("oops, no new instance created?");
}
You'll see that this won't print anything.