Common Type System—Properties
Properties
A property is metadata syntactic sugar. There is no special support for properties in the CTS, but they do
have both library and language support, and represent a very convenient way of defining methods for
accessing and manipulating state on an instance. They are marked with specialname in the IL to indicate
their special status. These are often called getters and setters. Instead of exposing fields directly to callers,
you can encapsulate access to them in small methods; these methods can perform lazy initialization, for
example, or any other logic that might be appropriate.
The C# language has explicit support for properties as a first class language feature. For example, consider an example that exposes two public fields:
class PropertyExample { public int X; public int Y; }
This example will function just fine, but it breaks one of the fundamental principles of OO design:
encapsulation. A better way to implement this is by controlling access to these fields through methods.
In languages such as Java, this would be done through the convention of providing int getX(), void setX(int x), and similar methods. But with C#, you need not rely on conventions, for example:
class PropertyExample { private int x; private int y; public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } }
This gives callers the means to access and set the values of X and Y but also gives the PropertyExample
type a way to control such access. All property accesses go through the get and set bodies. If you look
at the IL that gets generated, you’ll see get_X, set_X, get_Y, and set_Y methods; these are abstracted
away by the C# compiler.
Note that you needn’t provide both a getter and a setter but instead can just offer one of the two. Providing a getter but not a setter, for example, has the effect of creating a read-only property. Lastly, it might be obvious, but the accessibility of the fields to which the properties refer should usually be more restricted than that of the properties themselves. If you supply a property yet clients can still directly access the fields, you haven’t taken advantage of the primary value of properties: encapsulation.
|

