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;
publicstring Title
{
get { return _title; }
set { _title = value; }
}
Now the C# 3.0 auto-implemented code:
publicstring 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:
publicstring 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.
This entry was posted in .NET, C# and tagged .NET, C#. Bookmark the permalink. Both comments and trackbacks are currently closed.
Damien White is a developer in Connecticut that simply loves coding. Ever since he was young, he has had a driving passion for computers and software development, and a thirst for knowledge that just cannot be quenched. He’s happy to share what he knows in his quest to learn as much as possible.
C# 3.0 – Auto-Implemented Read-Only Properties
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.
Damien White is a developer in Connecticut that simply loves coding. Ever since he was young, he has had a driving passion for computers and software development, and a thirst for knowledge that just cannot be quenched. He’s happy to share what he knows in his quest to learn as much as possible.