views:

329

answers:

3

I have the following code:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(SqrtRoot(0));
        Console.WriteLine(SqrtRoot(10));
        Console.WriteLine(SqrtRoot(-10));
        Console.ReadKey();
    }

    public static int SqrtRoot(int i)
    {
        Contract.Requires(i >= 0);
        return (int)Math.Sqrt(i);
    }
}

I am running it in debug mode, and it should fire some kind of error in the last line

Console.WriteLine(SqrtRoot(-10));

altough, for some reason, it doesn't. It seems to ignore the Contract.Requires() call. Should I set up something when trying to use Code Contracts?

I'm using Visual Studio 2010 RC.

Thanks

A: 

I think you have to enable runtime contract checking in the project settings (there should be a "Code Contracts" pane...)

See the user documentation (section 6) for further information.

MartinStettner
I had thought of that, but I can't find it anywhere on the project's options.
devoured elysium
+2  A: 

I don't have that tab either but I found a workaround:

Contract.Requires<ArgumentOutOfRangeException>(i >= 0);

Probably the code contracts package must be installed but the download link is not working. http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx

Victor Hurdugaci
That will fire up an error if for values of i = 0, i = 10 and i = -10. I don't get it.
devoured elysium
I've just tried that with Contract.Requires<Exception>(i >= 0); and now the live is not greyed out. Maybe you have to give the exception type as Victor suggests.
Jason Evans
Hm... You're right. Something is not going well there... Even though the default behavior of contracts is to throw an error and display a window.
Victor Hurdugaci
I had to install Code Contracts from their site. Now it works as expected with Contract.Requires().
devoured elysium
+2  A: 

You need to install the Visual Studio integration. While the CodeContracts library itself is part of .NET 4, your code needs to be rewritten by the Code Contracts rewriter (ccrewrite) to actually use the library properly.

Download the installer from the DevLabs site.

Porges