Search code examples
c#propertiesmethods

Properties vs Methods


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.


Solution

  • 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.