Building Extensible Classes with Auto-implemented Properties

Auto-implemented properties are a language feature built into C# 3.0, and using them can have a positive impact on making maintenance easier in your code.  Often times we’re tempted to just create a class with fields rather than properties when we’re under the gun to get the code out the door or when we don’t think that we’ll need validation and/or properties to do validation later on.  So, if we are under the gun we might have some code that looks something like this (notice the AssetName in bold):

class Asset{    public string AssetName;
 private float _assetAmt;
 public float AssetAmount
 {
   get { return _assetAmt; }
   set{if (value >= 0){_assetAmt = value;
 }
 else  {
   throw new System.Exception("Asset cannot be less than zero value");}
 }
 }
}

However, we might need to change this code later - for example, when an Asset Name is required in a future version. But changing the AssetName field to a property can cause existing client code to break if we were to add validation to it when that code was expecting none. If we want to code classes that consider future changes and prevent client dependency problems, we could use auto-implemented properties. Auto-implemented properties allow the developer to use a short concise syntax to add in properties without having to write implementation code.  This means that we can have property stubs ready and when a future requirement demands that we add in necessary business logic, we can, without fear of breaking our dependencies. Here’s a sample of the same class with the AssetName as an auto-implemented property:

class Asset{ public string AssetName { get; set; }
private float _assetAmt; public float AssetAmount { get { return _assetAmt; } set{if (value >= 0){_assetAmt = value;} else{ throw new System.Exception("Asset cannot be less than zero value");}}}}

 It’s barely changed! Since we’ve added the auto-implemented AssetName property to the Asset class then we can easily extend it in the future, if warranted by adding the code to extend the getter and setter code blocks, making it very easy to upgrade code to fit future requirements.  Considering the very little effort and code it takes, there should be no reason to just go with fields in classes anymore.