Properties vs Methods

Trumpi picture Trumpi · Mar 2, 2009 · Viewed 53.4k times · Source

Quick question: When do you decide to use properties (in C#) and when do you decide to use methods?

We are busy having this debate and have found some areas where it is debatable whether we should use a property or a method. One example is this:

public void SetLabel(string text)
{
    Label.Text = text;
}

In the example, Label is a control on a ASPX page. Is there a principle that can govern the decision (in this case) whether to make this a method or a property.

I'll accept the answer that is most general and comprehensive, but that also touches on the example that I have given.

Answer

Ken Browning picture Ken Browning · Mar 2, 2009

From the Choosing Between Properties and Methods section of Design Guidelines for Developing Class Libraries:

In general, methods represent actions and properties represent data. Properties are meant to be used like fields, meaning that properties should not be computationally complex or produce side effects. When it does not violate the following guidelines, consider using a property, rather than a method, because less experienced developers find properties easier to use.