I think, the immutability of the strings in .NET is a thing, that confuses you.
The string is a reference type.
But it designed to be immutable.
This means, that you can't modify instances of System.String
. Every time you're doing any operation, that should modify string, it just creates a new instance of string. Look at this sample:
class A
{
private string someString;
public A(string someString)
{
this.someString = someString;
}
public string SomeString
{
get { return someString; }
}
public void DoSomething()
{
someString = someString + "_abc";
}
}
var sampleString = "Hello, world!";
var a = new A(sampleString);
Console.WriteLine(a.SomeString == sampleString); // prints 'true'
a.DoSomething();
Console.WriteLine(a.SomeString == sampleString); // prints 'false'
Console.WriteLine(sampleString); // prints 'Hello, world!'
Console.WriteLine(a.SomeString); // prints 'Hello, world!_abc'
Initially sampleString
and A.someString
are equal.
But after this line: someString = someString + "_abc"
the field A.someString
references another instance of string, because +
operator has created a new instance, and assignment operator has assigned that instance to A.someString
.
System.String
can't behave like Label
, because Label
is mutable. Hence, Label.Text = "Foobar";
doesn't create a new instance of label.
UPD.
If you want a mutable string, it already presents in FCL. This is StringBuilder
class.