Monday, July 18, 2005

Properties

I like Properties in C#, I think it begins to better define that space of functionality within a class that is not really a method but shouldn't just be a public member. In fact, according to MSDN protected instance fields and public instance fields should be used sparingly in C#.

A property is preferable to using a protected or public instance field.

From here.

I think this decoupling is good. It provides another layer of abstraction and allows the class designer to be a bit clever about what they expose and how they expose it.

Interestingly, I just found out that in addition to placing an access modifier on the Property itself, you can also apply one individually to the get/set. So, you could expose the "get" publically but make the set protected. For example,

public Size Size
{
get{ return _size; }
protected set { _size = value; }
}

I should mention that in my short experience with using interfaces in C#, I don't believe that it is possible to declare an access modifier on a Property (or its accessors) in an interface.

No comments: