Wednesday, September 14, 2011

Code Contracts in .NET 4.0

Today I started using a new .NET 4.0 feature called “code contracts” in my Visual Studio solutions. What these do is enable you to enforce preconditions and postconditions in your .NET methods. So for instance, a method that previously looked like this:

public static string GetValue(string key)
{
  if (string.IsNullOrEmpty(key))
  {
    throw new ArgumentException("Key is required.");
  }


  string result = default(string);

  // Code to determine result...

  if (string.IsNullOrEmpty(result))
  {
    throw new Exception("Unable to determine Value based on Key.");
  }


  return result;
}


Can be simplified to this:

using System.Diagnostics.Contracts;

//...

public static string GetValue(string key)
{
  Contract.Requires(
    !string.IsNullOrEmpty(key),
    "Key is required.");
  Contract.Ensures(
    !string.IsNullOrEmpty(Contract.Result()),
    "Unable to determine Value based on Key.");

  // Code to determine and return result...
}

Obviously the more checks your method has, the more it simplifies thingsRequires checks a precondition, and Ensures checks a postcondition.

Support for code contracts is baked in to .NET 4.0, but you need to install an additional component to enable design-time support in Visual Studio. You can download it from here: http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx. Make sure you close any running instances of VS prior to installing.

After the install you’ll have an extra "Code Contracts" page in your project’s property pages. The only settings I’ve changed are:
  • Assembly Mode: Standard Contract Requires – according to the doco it sounds as though you should use this unless you have a good reason not to.
  • Perform Runtime Contract Checking: Checked – without this, your contracts won’t be enforced.
  • Assert on Contract Failure: Checked – I check this for my Debug build so that I get a visible Assert message when my contracts are violated.
Some more information here:
I’ve only just started using this, so my understanding will probably evolve as time goes on, but it looks pretty useful.

No comments:

Post a Comment