Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
In c#4.0 i can use accessers on properties and the compiler creates a field under the hood matching this.

C#
public string Name
{
    get;
    private set;
}


Isn't creating a field for name unnecessary?
Or have i missed out anything?

Thanks,
/Johan
Posted
Updated 5-Dec-11 4:33am
v2

That is called an Automatic, or Auto-Implemented Property[^] - it is a way to declare a simple property that you do not intend to use any custom processing with. The compiler automatically creates the backing field for you.
 
Share this answer
 
Comments
Wonde Tadesse 5-Dec-11 11:29am    
5+
It isn't unnecessary if you understand that properties never store any values by themselves. To be able to store anything, properties must have a field to do so. Properties are really just syntactic sugar for combining two common operations (get and set) into one clean interface.

For automatic properties, .NET has done the legwork for you of creating a field to back this property. If it didn't, you couldn't store any values on your object.
 
Share this answer
 
Comments
Wonde Tadesse 5-Dec-11 11:29am    
5+
That's a perfectly reasonable construct for a property. You may only want a consumer object to be able to get a property's value, but not necessarily be able to set the property's value from an external source.

Many .Net classes have properties defined in just such a way.
 
Share this answer
 
v2
Comments
Wonde Tadesse 5-Dec-11 11:29am    
5+

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900