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:
Now the C# 3.0 auto-implemented code:
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:
Now, with this implementation, we can set the property in the class and it will be read-only when it is being used.