December 20, 2014
Hot Topics:

Understanding and Benefiting from Code Contracts in .NET 4.0

  • September 4, 2009
  • By Jani Järvinen
  • Send Email »
  • More Articles »
Presently, there is no easy solution to this, but you can leverage the fact that the RuntimeContractsAttribute (defined in the System.Diagnostics.Contracts namespace) attribute is defined in the assembly whenever runtime checks are enabled. For instance, you could then call Assert.Inconclusive if the attribute is not present.

Here is an example of such a check:

  [ClassInitialize()]
  public static void MyClassInitialize(
    TestContext testContext)
  {
    Type classToTest = typeof(NumericSamples);
    object[] attributes = classToTest.Assembly.
      GetCustomAttributes(typeof(
      RuntimeContractsAttribute), false);
    if (attributes.Length == 0)
    {
      Assert.Inconclusive("Code Contracts " +
        "runtime checks are not enabled.");
    }
  } 

Here, the type information of the tested class (here, NumericSamples) is retrieved, and then the custom attributes of the assembly are fetched. If a RuntimeContractsAttribute does not exist, then the Assert.Inconclusive method is called.

Note that with the current Visual Studio 2010 Beta 1 and the May, 2009 version of Code Contracts, the above code fails to compile if you do enable runtime checks. In this case, the error message will be similar to the following:

  
The type 'System.Diagnostics.Contracts.RuntimeContractsAttribute' 
exists in both 
'C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\mscorlib.dll' 
and 
'C:\...\ContractsTest.exe'

A solution to this is not presently available, but future Visual Studio betas and/or Code Contract versions will surely address the problem.

Conclusion

In this article, you learned about Code Contracts, a new set of classes and routines planned for inclusion in .NET Framework 4.0. Presently, Code Contracts is available on MSDN DevLabs (version 1.2.20518.12 being the latest one at this writing), and is compatible with both Visual Studio 2008 and Visual Studio 2010.

Both Visual Studio versions require you to set up the DevLabs installation package especially for the static check to work. However, it is easier to get started with the latest Visual Studio 2010 beta as no manual assembly references need to be set.

When studying Code Contracts, the main question often becomes: do you really need Code Contracts, or can you live simply with the old Assert method and manual if...throw tests if conditions are not met? The ability of Code Contracts to do static analysis on the code is a very important benefit, and should be used whenever possible. In the current version the static analysis is still somewhat sluggish and not stellar in intelligence, but it is a good start.

At runtime, the behavior of Code Contracts is roughly the same as with exceptions and assertions. This might lead you to think twice about using Code Contracts. However, you should keep in mind that you will then miss the versatility that Code Contracts provides, and also you won't find a substitute for object invariants. There are already several options that you can customize, and for instance enable only partial rule evaluation at runtime. This can both aid application performance and also help with unit testing.

Presently, the best overall solution seems to combine static Code Contracts analysis with Visual Studio Team System's Code Analysis. If you can upgrade Visual Studio Professional to a Team Edition, then you will get a wide range of feedback already at compile time. If you additionally have a comprehensive set of unit tests, then you will have a healthy process that is able to deliver quality code with three distinct checks.

But even with a lesser Visual Studio version available, Code Contract can be a highly valuable addition to your defensive programming toolbox. In this light, it's worth learning well, despite the few pre-release oddities.

Happy contract-based developing!

Resources

Code Contracts on MSDN DevLabs
Code Contracts documentation
Code Contracts on Microsoft Research
Code Contracts in .NET

About the Author

Jani Järvinen is a software development trainer and consultant in Finland. He is a Microsoft C# MVP, a frequent author and has published three books about software development. He is the group leader of a Finnish software development expert group at ITpro.fi and a board member of the Finnish Visual Studio Team System User Group. His blog can be found at http://www .saunalahti.fi/janij/. You can send him mail by clicking on his name at the top of the article.

>



Page 4 of 4



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel