In C# , Are Value types mutable or immutable ?

Kuntady Nithesh picture Kuntady Nithesh · Aug 17, 2011 · Viewed 11k times · Source

Value types behavior shows that whatever value we are holding cannot be changed through some other variable .

But I still have a confusion in my mind about what i mentioned in the title of this post . Can anyone clarify?

Answer

dlev picture dlev · Aug 17, 2011

Value types can be either mutable or (modulo some weird edge cases) immutable, depending on how you write them.

Mutable:

public struct MutableValueType
{
    public int MyInt { get; set; }
}

Immutable:

public struct ImmutableValueType
{
    private readonly int myInt;
    public ImmutableValueType(int i) { this.myInt = i; }

    public int MyInt { get { return this.myInt; } }
}

The built-in value types (int, double and the like) are immutable, but you can very easily create your own mutable structs.

One piece of advice: don't. Mutable value types are a bad idea, and should be avoided. For example, what does this code do:

SomeType t = new SomeType();
t.X = 5;

SomeType u = t;
t.X = 10;

Console.WriteLine(u.X);

It depends. If SomeType is a value type, it prints 5, which is a pretty confusing result.

See this question for more info on why you should avoid mutable value types.