C# 3.0 – Auto-Implemented Read-Only Properties

August 22, 2008 • Damien White

This isn’t a new topic by far, but I still encounter the question of how to implement a read-only auto-implemented property, so here it goes.

As I’m sure you are aware, C# 3.0 has a wonderful feature known as auto-implemented properties (sometimes referred to as Automatic Properties). These clean up our code quite a bit when we have properties that are simply backed by a private member, and all we do it get and set that value.

For example, the “old” way:

string _title;

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

Now the C# 3.0 auto-implemented code:

public string Title { get; set; }

Much cleaner. Behind the scenes C# takes care of the private member variable. This is great for get/set but what about for a read-only property? If you get rid of the “set” like you normally would, that works to retrieve the property, but we are never able to set it so it will always be the default value that is returned. Instead, we write the following code:

public string Title { get; private set; }

Now, with this implementation, we can set the property in the class and it will be read-only when it is being used.

Posted in .net, c# and tagged with .NET, C#

Damien White

I am a software architect with over 16 years of experience. I simply love coding! I have a driving passion for computers and software development, and a thirst for knowledge that just cannot be quenched. I'm happy to share what I know in my quest to learn as much as possible. I focus most of my time on web development using Ruby on Rails, Ember.js, and ASP.NET MVC.

comments powered by Disqus