Read-only Auto Properties

In this article I discuss read-only automatic properties. I am going to cover how automatic properties have changed over the releases of C# and along the way show how much more concise the code becomes.

Automatic Properties

Ever since C# 3.0 came out we had the ability to define automatic properties. Gone were the days of defining properties this way:

public class Dog
{

  private string _name;
  public Dog(string name)
  {
    Name = name;
  }

  public string Name
  {
    get { return _name; }
    set { _name = value; }
  }
}  

Or so we thought, we had this new super automatic properties syntax, that would save our fingers and keep us working as programmers for a bit longer.

When using the automatic property syntax, the compiler creates a private anonymous backing field, this can only be accessed through the property’s get and set accessors.

public class Dog
{
  public Dog(string name)
  {
    Name = name;
  }

  public string Name { get; set; }
}  

Read-Only Property

But how about if we want to make the Name property read-only? Well we would have to revert back to our original property syntax.

public class Dog
{
  private readonly string _name;
  public Dog(string name)
  {
    _name = name;
  }

  public string Name
  {
    get { return _name; }
  }
}  

Read-only Automatic Properties

When C# 6 came out, we were introduced to read-only automatic properties, this improves the above code with a much more concise syntax.

public class Dog
{
  public Dog(string name)
  {
    Name = name;
  }


  public string Name { get; }
}

Conclusion

We can create immutable types with a more concise syntax, i also think this syntax has the benefit of being more readable.