-1

Now, to me, strings have always been value types. Learning that they're not, and are in fact what's called Immutable String is very interesting, but holds a very important question:

When would a string not be an immutable string?

See, when I declare a string like this:

string testString = "abc";

The stack should now hold the variable declaration and the heap the value, to which the variable is referencing. If I declared a second string:

string secondString = testString;

Both variables should now reference the same position on the heap. If I did this:

secondString = testString + "def";

The value on the heap should be copied, modified and a second value should lie on the heap.

I understand this is what an immutable string is.

But since this is pretty much how I've always been declaring and working with strings, I wonder if there is another way, a mutable string, so to say.

trincot
  • 317,000
  • 35
  • 244
  • 286
Xaphas
  • 501
  • 4
  • 20

1 Answers1

1

Firstly, strings are immutable and that's that.

var string1 = "string";
var string2 = string1;
string2 = "string2";

Console.WriteLine(string1);
Console.WriteLine(string2);

Output

string
string2

Secondly, why do you really want an mutable string? Here are many reasons why strings "are" immutable. see Why .NET String is immutable?

Lastly, if you really want an immutable string you can create an instance of StringBuilder You get mutability, however it will reallocate its internal buffer every-time it needs to, or you can roll your own fancy pants class.

Sir Rufo
  • 18,395
  • 2
  • 39
  • 73
TheGeneral
  • 79,002
  • 9
  • 103
  • 141