Why Are C# Structs Immutable

Why are C# structs immutable?

If this subject interests you, I have a number of articles about immutable programming at https://ericlippert.com/2011/05/26/atomicity-volatility-and-immutability-are-different-part-one/

I was just curious to know why structs, strings etc are immutable?

Structs and classes are not immutable by default, though it is a best practice to make structs immutable. I like immutable classes too.

Strings are immutable.

What is the reason for making them immutable and rest of the objects as mutable.

Reasons to make all types immutable:

  • It is easier to reason about objects that do not change. If I have a queue with three items in it, I know it is not empty now, it was not empty five minutes ago, it will not be empty in the future. It's immutable! Once I know a fact about it, I can use that fact forever. Facts about immutable objects do not go stale.

  • A special case of the first point: immutable objects are much easier to make threadsafe. Most thread safety problems are due to writes on one thread and reads on another; immutable objects don't have writes.

  • Immutable objects can be taken apart and re-used. For example, if you have an immutable binary tree then you can use its left and right subtrees as subtrees of a different tree without worrying about it. In a mutable structure you typically end up making copies of data to re-use it because you don't want changes to one logical object affecting another. This can save lots of time and memory.

Reasons to make structs immutable

There are lots of reasons to make structs immutable. Here's just one.

Structs are copied by value, not by reference. It is easy to accidentally treat a struct as being copied by reference. For example:

void M()
{
S s = whatever;
... lots of code ...
s.Mutate();
... lots more code ...
Console.WriteLine(s.Foo);
...
}

Now you want to refactor some of that code into a helper method:

void Helper(S s)
{
... lots of code ...
s.Mutate();
... lots more code ...
}

WRONG! That should be (ref S s) -- if you don't do that then the mutation will happen on a copy of s. If you don't allow mutations in the first place then all these sorts of problems go away.

Reasons to make strings immutable

Remember my first point about facts about immutable structures staying facts?

Suppose string were mutable:

public static File OpenFile(string filename)
{
if (!HasPermission(filename)) throw new SecurityException();
return InternalOpenFile(filename);
}

What if the hostile caller mutates filename after the security check and before the file is opened? The code just opened a file that they might not have permission to!

Again, mutable data is hard to reason about. You want the fact "this caller is authorized to see the file described by this string" to be true forever, not until a mutation happens. With mutable strings, to write secure code we'd constantly have to be making copies of data that we know do not change.

What are the things that are considered to make an object immutable?

Does the type logically represent something that is an "eternal" value? The number 12 is the number 12; it doesn't change. Integers should be immutable. The point (10, 30) is the point (10, 30); it doesn't change. Points should be immutable. The string "abc" is the string "abc"; it doesn't change. Strings should be immutable. The list (10, 20, 30) doesn't change. And so on.

Sometimes the type represents things that do change. Mary Smith's last name is Smith, but tomorrow she might be Mary Jones. Or Miss Smith today might be Doctor Smith tomorrow. The alien has fifty health points now but has ten after being hit by the laser beam. Some things are best represented as mutations.

Is there any difference on the way how memory is allocated and deallocated for mutable and immutable objects?

Not as such. As I mentioned before though, one of the nice things about immutable values is that something you can re-use parts of them without making copies. So in that sense, memory allocation can be very different.

How do I make a struct immutable?

Make the fields private readonly and pass the initial values in the constructor

public struct ImmutableStruct
{
private readonly int _field1;
private readonly string _field2;
private readonly object _field3;

public ImmutableStruct(int f1, string f2, object f3)
{
_field1 = f1;
_field2 = f2;
_field3 = f3;
}

public int Field1 { get { return _field1; } }
public string Field2 { get { return _field2; } }
public object Field3 { get { return _field3; } }
}

Starting with C#6.0 (Visual Studio 2015) You can use getter only properties

public struct ImmutableStruct
{
public ImmutableStruct(int f1, string f2, object f3)
{
Field1 = f1;
Field2 = f2;
Field3 = f3;
}

public int Field1 { get; }
public string Field2 { get; }
public object Field3 { get; }
}

Note that readonly fields and getter only properties can be initialized either in the constructor or, in classes, also with field or property initializers public int Field1 { get; } = 7;.

It is not guaranteed that the constructor is run on a struct. E.g. if you have an array of structs, you must then call the initializers explicitly for each array element. For arrays of reference types all the elements are first initialized to null, which makes it obvious that you have to call new on each element. But it is easy to forget it for value types like structs.

var immutables = new ImmutableStruct[10];
immutables[0] = new ImmutableStruct(5, "hello", new Person());
immutables[1] = new ImmutableStruct(6, "world", new Student());
...

Starting with C# 7.2, you can use Read-only structs


Starting with C# 9.0 there is yet another option: the Init-Only Properties. Read-only fields and get-only auto implemented properties can be initialized in a constructor and in the field or property initializer but not in an object initializer.

This is the motivation for introducing init-only properties. They replace the set accessor by an init accessor. This extends the mutation phase from the actual object creation to the entire object construction phase including object initializers and with expressions (also a new C# 9.0 feature).

public string Name { get; init; }

Usage:

var x = new ImmutableStruct { Name = "John" }; // Okay

x.Name = "Sue"; // Compiler error CS8852: Init-only property or indexer
// 'ImmutableStruct.Name' can only be assigned in an object
// initializer, or on 'this' or 'base' in an instance constructor
// or an 'init' accessor.

C# 10.0 (Visual Studio 2022) introduces Record structs, Parameterless struct constructors and field initializers.

readonly record struct Point(int X, int Y);

This generates X and Y properties with get and init accessors.

Immutability of structs

Structs should represent values. Values do not change. The number 12 is eternal.

However, consider:

Foo foo = new Foo(); // a mutable struct
foo.Bar = 27;
Foo foo2 = foo;
foo2.Bar = 55;

Now foo.Bar and foo2.Bar is different, which is often unexpected. Especially in the scenarios like properties (fortunately the compiler detect this). But also collections etc; how do you ever mutate them sensibly?

Data loss is far too easy with mutable structs.

Immutable structure in c#

Structs in C# are not immutable by default. To mark a struct immutable, you should use the readonly modifier on the struct. The reason your properties aren't updating is that your syntax is wrong. You should use the value keyword to dereference the value provided to the setter.

public int Age
{
get
{
return age;
}
set
{
age = value; // <-- here
}
}

Why are mutable structs “evil”?

Structs are value types which means they are copied when they are passed around.

So if you change a copy you are changing only that copy, not the original and not any other copies which might be around.

If your struct is immutable then all automatic copies resulting from being passed by value will be the same.

If you want to change it you have to consciously do it by creating a new instance of the struct with the modified data. (not a copy)

Immutable class vs struct


Since copying reference is cheaper than copying struct, why would one use an immutable struct?

This isn't always true. Copying a reference is going to be 8 bytes on a 64bit OS, which is potentially larger than many structs.

Also note that creation of the class is likely more expensive. Creating a struct is often done completely on the stack (though there are many exceptions), which is very fast. Creating a class requires creating the object handle (for the garbage collector), creating the reference on the stack, and tracking the object's lifetime. This can add GC pressure, which also has a real cost.

That being said, creating a large immutable struct is likely not a good idea, which is part of why the Guidelines for choosing between Classes and Structures recommend always using a class if your struct will be more than 16 bytes, if it will be boxed, and other issues that make the difference smaller.

That being said, I often base my decision more on the intended usage and meaning of the type in question. Value types should be used to refer to a single value (again, refer to guidelines), and often have a semantic meaning and expected usage different than classes. This is often just as important as the performance characteristics when making the choice between class or struct.

C# Structs: Mutability versus Performance

There are two distinct usage cases for structs; in some cases, one wants a type that encapsulates a single value and behaves mostly like a class, but with better performance and a non-null default value. In such cases, one should use what I would call an opaque structure; MSDN's guidelines for structures are written on the assumption that this is the only usage case.

In other cases, however, the purpose of the struct is simply to bind some variables together with duct tape. In those cases, one should use a transparent struct which simply exposes those variables as public fields. There is nothing evil about such types. What's evil is the notion that everything should behave like a class object, or that everything should be "encapsulated". If the semantics of the struct are such that:

  1. There is some fixed set of readable members (fields or properties) which expose its entire state
  2. Given any set of desired values for those members, one can create an instance with those values (no combinations of values are forbidden).
  3. The default value of the struct should be to have all those members set to the default values of their respective types.

and any change to them would break the code which uses it, then there is nothing which future versions of the struct could possibly do which a transparent struct would not be able to do, nor is there anything that a transparent struct would allow which a future version of the struct would be able to prevent. Consequently, encapsulation imposes cost without adding value.

I would suggest that one should endeavor to, whenever practical, make all structs either transparent or opaque. Further, I would suggest that because of deficiencies in the way .net handles struct methods, one should avoid having opaque structures' public members modify this except perhaps in property setters. It is ironic that while MSDN's guidelines suggest one shouldn't use a struct for things that don't represent a "single value", in the common scenario where one simply wants to pass a group of variables from one piece of code to another, transparent structs are vastly superior to opaque structs or class types, and the margin of superiority grows with the number of fields.

BTW, with regard to the original question, I would suggest that it's useful to represent that your program may want to deal with two kinds of things: (1) a car, and (2) information related to a particular car. I would suggest that it may be helpful to have a struct CarState, and have instances of Car hold a field of type CarState. This would allow instances of Car to expose their state to outside code and possibly allow outside code to modify their state under controlled circumstances (using methods like

delegate void ActionByRef<T1,T2>(ref T1 p1, ref T2 p2);
delegate void ActionByRef<T1,T2,T3>(ref T1 p1, ref T2 p2, T3 p3);

void UpdateState<TP1>(ActionByRef<CarState, TP1> proc, ref TP1 p1)
{ proc(ref myState, ref p1); }
void UpdateState<TP1,TP2>(ActionByRef<CarState, TP1,TP2> proc, ref TP1 p1, ref TP2 p2)
{ proc(ref myState, ref p1, ref p2); }

Note that such methods offer most of the performance advantages of having the car's state be a mutable class, but without the dangers associated with promiscuous object references. A Car can let outside code may update a car's state via the above methods without allowing outside code to modify its state at any other time.

BTW, I really wish .net had a way of specifying that a "safe" struct or class should be considered as encapsulating the members of one or more of its constituents [e.g. so that struct which held a Rectangle called R and an String called Name could be regarded as having a fields X, Y, Width, and Height which alias the corresponding struct fields. If that were possible, it would greatly facilitate situations where a type needs to hold more state than previously expected. I don't think the present CIL allows for such aliasing in a safe type, but there's no conceptual reason it couldn't.

Immutable class vs Immutable struct

Generally, no, you should not change it to a struct. Just because it's immutable doesn't mean that it's automatically a good candidate for being a struct.

A struct should be small. With your four ints it's just at the recommended limit of 16 bytes where performance for structs starts to degrade.

A struct should represent a single entity of some kind. Perhaps your class does that, but from your description it doesn't sound likely.

A structure is harder to implement correctly than a class. It should behave well to things like comparisons, so there are more things to implement than what is expected of a class.

Unless you have a really good reason to implement it as a struct, like performance issues, you should keep your class as a class.

Are readonly structs supposed to be immutable when in an array?


Is this behaviour correct?

Yes. A readonly struct does not change the mutability of the variable which holds a copy of the struct! Array elements are variables and variables can vary.

You don't need to use C# 7.2 to see this. Integers are immutable; there's no way to turn the integer 3 into the integer 4. Rather, you replace the contents of a variable containing 3 with 4. The fact that integers are immutable doesn't make variables into constants. Same here. The struct is immutable, just like an int, but the variable holding it is mutable.

Similarly, a readonly field on a struct is a lie; that field can be observed to change because structs do not own their storage. See Does using public readonly fields for immutable structs work? for more on this.

(And of course everything is mutable if you break the rules of the language and runtime by using reflection at a high trust level or unsafe code.)



Related Topics



Leave a reply



Submit