Dennis van der Stelt

If you have one problem and use cache to solve it, you now have two problems.

Community

Email Notifications

News

  • Addicted to Refactor! Pro

I read...

I Use...

Tags

Recent Posts

Archives

Blog Subscription Form

  • Email Notifications
    Go

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.

Comments

Miron said:

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;

   }

 }

# March 25, 2008 10:24 PM

Dennis van der Stelt said:

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; }

}

# March 26, 2008 8:44 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Please add 7 and 3 and type the answer here: