Wednesday, December 8, 2010

Code Contracts in .NET 4

Reference : http://visualstudiomagazine.com/articles/2010/06/23/code-contracts.aspx
http://www.codeproject.com/KB/cs/CodeContracts.aspx

One of the key features of the .NET Framework is its enforcement of strong typing. But sometimes, simply enforcing that an integer is passed into a method isn't enough. We have to write additional code to make sure the integer is in a particular range or some other requirement. With Code Contracts, we get a language-neutral way to express such additional requirements in the form of preconditions, postconditions and invariants.
What is Code Contracts
Code Contracts is a subset of a larger Microsoft Research Project called Spec# (pronounced "Spec Sharp"). You can read more about this project here. Spec# is a formal language for defining API contracts. A subset of these contracts -- preconditions, postconditions and invariants -- has made its way into Visual Studio 2010 in the form of Code Contracts.
Before being able to utilize Code Contracts, you'll need to download and install it from http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx. Why the need for the download? Code Contracts has support for both Visual Studio 2008 as well as 2010. Since it's not a VS 2010-specific product, a separate download is required.
Example :
using System.Diagnostics.Contracts;

public class TestContract
    {
        int m_n1;
        int m_n2;
        public TestContract(int x,int y)
        {
            Contract.Requires(x > 10, "x should be > 10");
            m_n1 = x;
            m_n2 = y;
        }       
    }


Now try to create an object of TestContract
                TestContract obj = new TestContract(3, 20);

This will throw exception as “x should be > 10”

No comments:

Post a Comment