Read-only 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.

You may also like...

2 Responses

  1. Miron says:

    this is nice useful feature. However, there is it possible to have default value to a properties ?
    equivalent to:

    private string _title = “Hello”;
    public string Title
    {
    get { return _title; }
    private set
    {
    _title = value;
    }
    }

  2. I have something against setting these values in class-scope. Just doesn’t feel right! 🙂
    My way would be to do it like this:

    class MyClass
    {
    private string _title;

    // constructor
    public MyClass()
    {
    Title = “Hello world”;
    }

    public string Title
    {
    get { return _title; }
    set { _title = value; }
    }
    }

    which in automatic-property world would result in

    class MyClass
    {
    // constructor
    public MyClass()
    {
    Title = “Hello world”;
    }

    public string Title { get; set; }
    }

Click on a tab to select how you'd like to leave your comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.