.NET 4.0 Code Contracts

One of the great features of .NET 4.0 is Code Contracts. Code Contracts aid in the unit testing process of code and make catching bugs before deploying the code much easier.

This post shows a sneak preview of Code Contracts in .NET Beta1 and VS 2010 Beta1. Note that by the time of the current writing, you need to install an Add-On to visual studio 2010 in order to work with code contracts.

To do so, go to the following URL and download and install Code Contracts for .NET VSTS edition.
http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx#2

once done, you will notice a new tab appearing in the Project Properties window. This tab is shown below:

Now to test how Code Contracts work, consider the below code

class Ctrct
{
public int Divide(int x, int y, ref int z)
{
Contract.Requires(y > 0);
Contract.Ensures(z > 1);

z = x / y;

return z;

}
}

This class has a method that simply divides two numbers. First notice the line
Contract.Requires(y > 0);
This line indicates that y should be greater than zero otherwise the code will fail. This check will happen before the execution of the method.

The second line is
Contract.Ensures(z > 1);
This line indicates that by the time the method ends, z should be greater than 1 else the code will fail.

Now test with the above code passing first y=0 and you will find that the method fails at the entry level. Now even more interesting, pass y=1 and x=1; in this case the code will execute and z will be calculated to 1. in this case after the return statement is executed, the method will still fail. that is because the post condition of z being greater than one is not met. execution won’t be delivered to the caller even though the return statement is executed!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s