Mutable vs Immutable Objects

A mutable object can be changed after it's created, and an immutable object can't.

In C#, mutable types, like lists, can be modified:

var list = new [] { 4, 9 }; list[0] = 1; // list is now [1, 9]

Immutable types, like tuples, can't be changed:

var tuple = new Tuple<int, int> (4, 9); tuple.Item1 = 1; // Doesn't compile, since tuples are read only

Strings can be mutable or immutable depending on the language.

Strings are immutable in C#.

When you modify a string, you're actually creating a separate copy, leaving the first intact:

var testString = "mutable?"; testString[7] = '!'; // compile-time error

But in some other languages, like C++, strings can be mutable:

string testString("mutable?"); testString[7] = '!'; // testString is now "mutable!"

If you want mutable strings in C#, you can use a StringBuilder object:

using System.Text; var mutableString = new StringBuilder("mutable?"); mutableString.Replace("?", "!"); // Still the same object! // mutableString is now "mutable!" // Convert to an immutable string var immutableString = mutableString.ToString();

Or, you can convert the string to an array of characters, which will be mutable.

Mutable objects are nice because you can make changes in-place, without allocating a new object. But be careful—whenever you make an in-place change to an object, all references to that object will now reflect the change.

. . .