Static Checking .NET Code Contracts

by Doug Finke on February 27, 2010

in .NET 4.0,Code Contracts,Static Checking

For those familiar with Debug.Assert, you may be thinking this is a solved problem. But Debug.Assert only allows you to express that a particular condition should be true at a particular point in the code. Code contracts allow you to declare once that a particular condition should hold any time certain events occur, such as every exit point from a method.

MSDN Magazine Code Contracts

A Precondition Example

After enabling static checking, you can write code and VS 2010 will indicate Code Contract issues with squiggles and tooltips.

image 

Use the project properties Code Contracts tab to enable Squiggles

To get the tab to appear, you need to download the static checker from DevLabs: Code Contracts.

image

{ 1 comment… read it below or add one }

Josh Einstein 02.27.10 at 8:15 pm

Ahh thanks! I had started replacing my ParameterValidation.ThrowIfNull checks with Contract checks and I was expecting compiler assistance but I didn’t realize I had to enable static checking too.

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>