Since C# provides the ability for developers to write both methods and properties, it may be difficult to understand the difference or to know when to use one or the other. Sometimes the decision to use one over the other isn’t completely clear. Fortunately there are plenty of resources available to help out.
A simple Google search on the topic will yields many results, however Microsoft has some pretty straightforward guidelines on the topic. To quote the linked guidelines, “class library designers often must decide between implementing a class member as a property or a method. In general, methods represent actions and properties represent data…”
Here are the basic guidelines to follow:
- Use a property when the member is a logical data member
- Use a method when:
- The operation is a conversion, such as Object.ToString.
- The operation is expensive enough that you want to communicate to the user that they should consider caching the result.
- Obtaining a property value using the get accessor would have an observable side effect.
- Calling the member twice in succession produces different results.
- The order of execution is important. Note that a type’s properties should be able to be set and retrieved in any order.
- The member is static but returns a value that can be changed.
- The member returns an array. Properties that return arrays can be very misleading. Usually it is necessary to return a copy of the internal array so that the user cannot change internal state. This, coupled with the fact that a user can easily assume it is an indexed property, leads to inefficient code.
One example of this is something I’ve pointed out already for the
IEnumerable.Count() method. In the article I mentioned that calling
Count() on an
IEnumerable is an expensive call. The fact that it’s a method here indicates this. This is expensive because calling the method causes an iteration over the whole object to actually determine the count. Until that operation occurs, the count is not just simply access to known data. Instead, on a
List<T> there’s a
Count property and on an array there’s a
Length property. In these cases, the count/length are already know, so the properties just indicate access to know data.
- Properties should not return arrays
- Choosing Between Properties and Methods
- C#: Properties versus getter methods