When coding C# I often find myself implementing immutable types.
I always end up writing quite a lot of code and I am wondering whether there is a faster way to achieve it.
What I normally write:
public struct MyType
{
private Int32 _value;
public Int32 Value { get { return _value;} }
public MyType(Int32 val)
{
_value = val;
}
}
MyType alpha = new MyType(42);
This gets fairly complicated when the number of fields grows and it is a lot of typing.
Is there a more efficient way for doing this?
The only way I can suggest of writing less code is to use something like ReSharper to auto-generate the code for you. If you start with something like:
you can then generate “read-only properties” to give:
followed by generate constructor to give:
The generation steps are 8 key presses in total.
If you really want an unmodifiable immutable class, I would declare it as such:
This makes the class non-derivable (meaning that a sub-class cannot modify its inner state), and the
_valueproperty assignable only during construction. Unfortunately, ReSharper doesn’t have code generation for this pattern, so you would still have to construct (most of) it manually.