Properties and Accessors

A property gives controlled access to the private local state of an object, either directly to its fields or via some computation. Properties define one or two accessors: get and/or set. The most common form of a property is:

public type Field {get; set;} 

Where Field is an identifier. This declaration creates a private field and makes it accessible for public reading and writing via the name Field.

By placing such properties in an interface, we are effectively requiring classes to supply property accessors as well as the usual methods when implementing the interface.

Properties can omit either the get or the set accessors; it is more typical to omit the set, which makes the property read-only.

Properties can also compute the result of a get or set, in which case, the expanded syntax is:

public type Field {
get { statements; return expression; }
set { statements including reference to value; }
} 

A property typically, but not necessarily, has access to a private type Field. value is the implicit parameter of a call to set a property.

reference. C# Language Specification Version 3.0, September 2007, Section 10.7

Leave a Reply