Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# , Are Value types mutable or immutable ?

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?

like image 381
Kuntady Nithesh Avatar asked Aug 17 '11 04:08

Kuntady Nithesh


1 Answers

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.

like image 102
dlev Avatar answered Sep 30 '22 02:09

dlev