kdbanman
kdbanman

Reputation: 10597

What is the most concise form of an immutable data class in C#?

I have an enum State and a class Neighborhood that uses them as data. I'm new to C#, so I'm not sure if this is idiomatic or could be more concise (or just plain wrong).

public enum State : byte
{
    zero = 0,
    one = 1,
    two = 2
}

public class Neighborhood
{

    private State _left, _center, _right;

    public Neighborhood(State left, State center, State right)
    {
        _left = left;
        _center = center;
        _right = right;
    }

    public State left { get { return _left; } }

    public State center { get { return _center; } }

    public State right { get { return _right; } }
}

Is there a shorter or more idiomatic way to do this?

Upvotes: 0

Views: 79

Answers (2)

Mathieu Guindon
Mathieu Guindon

Reputation: 71247

This might not be the most concise way of writing it, but there are a number of differences between using readonly backing fields and private set auto-properties:

  • private set implies that the class implementation can alter the value of the property.
  • readonly backing field can only be initialized from the constructor; the class implementation cannot alter its value.
  • readonly backing field better communicates the intent, if that intent is to make something immutable.
  • backing fields with a _namingConvention make the this qualifier redundant.
  • get-only property with a readonly backing field is inherently thread-safe; more information here.
public class Neighborhood
{
    public Neighborhood(State left, State center, State right)
    {
        _left = left;
        _center = center;
        _right = right;
    }

    private readonly State _left;
    public State Left { get { return _left; } }

    private readonly State _center;
    public State Center { get { return _center; } }

    private readonly State _right;
    public State Right { get { return _right; } }
}

Upvotes: 3

Emond
Emond

Reputation: 50712

public enum State : byte
{
    zero = 0,
    one = 1,
    two = 2
}

public class Neighborhood
{
    public Neighborhood(State left, State center, State right)
    {
        this.Left = left;
        this.Center = center;
        this.Right = right;
    }

    public State Left { get; private set; }

    public State Center { get; private set; }

    public State Right { get; private set; }
}

Upvotes: 3

Related Questions