Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently implement immutable types

Tags:

c#

c#-4.0

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?

like image 650
yas4891 Avatar asked Aug 29 '11 22:08

yas4891


People also ask

Does immutability of strings make Java more efficient or less efficient?

Strings immutability makes it possible to share them, this is more efficient memory-wise.

What makes immutability faster in Python?

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.

In which situations is it better to use an immutable object?

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.


2 Answers

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.

like image 154
adrianbanks Avatar answered Oct 04 '22 17:10

adrianbanks


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;
  }
}
like image 40
Ben Robinson Avatar answered Oct 04 '22 18:10

Ben Robinson