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?
Strings immutability makes it possible to share them, this is more efficient memory-wise.
Mutable and immutable objects are handled differently in python. Immutable objects are quicker to access and are expensive to change because it involves the creation of a copy. Whereas mutable objects are easy to change.
Immutable objects can be useful in multi-threaded applications. Multiple threads can act on data represented by immutable objects without concern of the data being changed by other threads. Immutable objects are therefore considered more thread-safe than mutable objects.
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:
public class MyType
{
private int _value;
}
you can then generate "read-only properties" to give:
public class MyType
{
private int _value;
public int Value{get {return _value;}}
}
followed by generate constructor to give:
public class MyType
{
private int _value;
public int Value{get {return _value;}}
public MyType(int value)
{
_value = value;
}
}
The generation steps are 8 key presses in total.
If you really want an unmodifiable immutable class, I would declare it as such:
public sealed class MyType
{
public int Value{get {return _value;}}
private readonly int _value;
public MyType(int value)
{
_value = value;
}
}
This makes the class non-derivable (meaning that a sub-class cannot modify its inner state), and the _value
property 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.
You could simplify it a little with automatic properties and a private setter as below:
public struct MyType
{
public Int32 Value { get; private set; }
public MyType(Int32 val)
{
Value = val;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With