Sep 1, 2010

Code Contracts in VS2008 and .NET 3.5

I’ve heard about code contracts for C# for a while but always in the context of Visual Studio 2010 and .NET 4.0. Today while reading the Code Contracts Page on DevLabs I saw that Code Contracts are supported in Visual Studio 2008. That page has buttons that let you download the file you’ll need to add code contracts to VS2008. Also notice that after installing under the Start menu there are samples and documentation. I did notice the documentation PDF from DevLabs page isn’t the latest available. At the time of this writing there is a July 2008 revision on the Microsoft Research Code Contract page and the DevLabs version was from June. Why are there are differences between DevLabs and Microsoft Research? Why are two sites needed for this technoloby? Good question, wish I had an answer. 

imageI have a fairly new project I’m working on so I decided to try writing a contract condition and compiling.  Watch the getting started video on channel 9 to get all the prerequisites. The first thing that happened was I got several warnings because other projects in my solution that were being included didn’t have a setting enabled for Code Contracts. The easiest fix was to go to each referenced project, pull up the properties page, go to the new Contracts tab and select the DoNotBuild option. Then I built those projects, returned to my original project and built it. Of course when I get around to adding contracts to those included assemblies I’ll change the setting to Build.

Playing Nice with ReSharper

I use ReSharper 5.0 and it seems like R# isn’t fully aware of data contracts. Adding the symbol CONTRACTS_FULL  to the conditional compilation symbols made R# realize these weren’t redundant method calls.

image

When creating invariant objects R# will flag the object as not being used. You can disable this by adding the [UsedImplicitly] attribute. You’ll need to references the JetBrains.Annotations.dll located in the .bin folder of your Resharper installation folder. You’ll also need to add a using for the JetBrains.Annotations namespace. When I have an invariant on a class that verifies that the object is not null

Contract.Invariant(_someObject != null);
and a later invariant that checks a property on that object,
Contract.Invariant(!String.IsNullOrEmpty( _someObject.Name));
R# flags _someObject.Name as a possible null reference exception. I haven’t figured out how to disable that warning without using the ugly commenting method.

About Me

My photo
Tod Gentille (@todgentille) is now a Curriculum Director for Pluralsight. He's been programming professionally since well before you were born and was a software consultant for most of his career. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.