I frequently read that struct
s should be immutable - aren\'t they by definition?
Do you consider int
to be immutable?
int i
I think the confusion is that if you have a reference type that should act like a value type it's a good idea to make it immutable. One of the key differences between value types and reference types is that a change made through one name on a ref type can show up in the other name. This doesn't happen with value types:
public class foo
{
public int x;
}
public struct bar
{
public int x;
}
public class MyClass
{
public static void Main()
{
foo a = new foo();
bar b = new bar();
a.x = 1;
b.x = 1;
foo a2 = a;
bar b2 = b;
a.x = 2;
b.x = 2;
Console.WriteLine( "a2.x == {0}", a2.x);
Console.WriteLine( "b2.x == {0}", b2.x);
}
}
Produces:
a2.x == 2
b2.x == 1
Now, if you have a type that you'd like to have value semantics, but don't want to actually make it a value type - maybe because the storage it requires is too much or whatever, you should consider that immutability is part of the design. With an immutable ref type, any change made to an existing reference produces a new object instead of change the existing one, so you get the value type's behavior that whatever value you're holding cannot be changed through some other name.
Of course the System.String class is a prime example of such behavior.