C#: Properties versus getter methods

You might be wondering why some classes in the .NET Framework have properties, other classes have GetXXX methods, and some have a combination of the two.  The reason is that the semantic, or meaning, is quite different.

Consider this class:

public class Customer
{
 public int CustomerID;
 public string FirstName;
 public string LastName;
 
 public Order[] GetOrders()
 {
  // do database work
 }
}

The CustomerID, FirstName, and LastName represent the customer state.  The orders are derived from the customer state using GetOrders().  In fact I do not support having method like this because it presumes that a canonical representation of Order exists.  That's another topic. 

A great rule-of-thumb regarding properties is to consider that the Visual Studio debugger executes the getter method when watching an object.  That is, property accessors are executed at unpredictable times and should thus not cause any discernable side-effects.  Abusing properties can lead to heisenbugs.

Another reason to use a method is that order retrieval is likely to be parameterized.

Finally, a good practice is for property access to be computationally cheap; client code should not be forced to place the property value into a local variable - it's premature optimization.  Expensive code should be placed in methods - client code is sure to store and reuse the result.  The exception is if the property getter method caches the result in a private field, which can be a challenge as the class instance is mutated.

The property syntax in .NET languages is not syntactic sugar.  It adds considerable richness to classes.

This article is part of the GWB Archives. Original Author: Eron Wright

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.