#702 – An Automatic Property Must Define Both get and set Accessors
October 29, 2012 3 Comments
When you define an automatic property, you must include both get and set accessors.
public string Name { get; set; }
It wouldn’t make sense to omit either accessor, since they are the only mechanism for reading from or writing to the property.
Although you can’t strictly create a read-only or write-only automatic property, you can use access modifiers so that the property is effectively read-only or write-only, from outside the class.
// Automatic property that is read-only from outside class public string Temperament { get; protected set; } // Automatic property that is write-only from outside class public string Password { protected get; set; }
Hi Sean.
IMO you can create a readonly property by only include get accessor:
public string Temperament { get; }
Regards.
Emilio,
Actually, automatic properties must define both get and set accessors. The line you show above would result in a compiler error.
You can, however, implement a read-only property by defining only a get accessor, if you’re defining a regular property, rather than an automatic property. So in your example, if you added a body to the get accessor, it would be allowed.
Yes, you’re absolutly right the get accessor must have a body to work so it’s not an automatic property.