Is this a proper way to declare immutable structs?
public struct Pair
{
public readonly int x;
public readonly int y;
// Constructor and stuff
}
As of C# 7.2, you can now declare an entire struct as immutable:
public readonly struct Pair
{
public int x;
public int y;
// Constructor and stuff
}
This will have the same effect as marking all of the fields as readonly, and will also document to the compiler itself that the struct is immutable. This will increase the performance of areas where the struct is used by reducing the number of defensive copies the compiler makes.
As noted in Eric Lippert's answer, this does not prevent the structure itself from being reassigned completely, and thus providing the effect of its fields changing out from under you. Either passing by value or using the new in parameter modifier can be used to help prevent this:
public void DoSomething(in Pair p) {
p.x = 0; // illegal
p = new Pair(0, 0); // also illegal
}