Readonly automatic property

Readonly automatic property

I got a question during my latest presentation about automatic properties (full name is actually automatically implemented properties) with just a ‘getter’. I could not remember the syntax, thought it was something with the readonly keyword. I was wrong, here’s the correct syntax.

public class Training
{
  public string Title { get; private set; }
  public int Days { get; set; }
}

Note that this does have a setter, although it’s set to private. The reason is that it’s otherwise impossible to actually set the Title of the training. Normally we would set the backing field ‘_title’, but as this is generated by the compiler, we can’t access it yet.

The equivalent is:

public class Training
{
  private string _title;
  private int _days;

  public string Title
  {
    get { return _title; }
    private set
    {
      _title = value;
    }
  }
  public int Days
  {
    get { return _days; }
    set { _days = value; }
  }
}

Note that the private setter is still there. You can remove it completely and set the backing field as explained.

Please enable JavaScript to view the comments.

pinch or scroll to zoom, drag to pan, esc to close