6

I'm using the 3.5 library for microsoft code contracts

public object RetrieveById(int Id)
{    
    //stuff happens...
    Contract.Ensures(newObject != null, "object must not be null");
    return newProject;
    //No error message if I move the Contract.Ensures to here
    //But it isn't asserting/throwing a contract exception here either           
}

I get the compiler message: "Error 18 Contract section within try block in method 'Controller.RetrieveById(System.Int32)'

UPDATE:

I figured it out with your help:

  • Move to top
  • Check against Contract.Result

    Contract.Ensures(Contract.Result() != null, "object must not be null ");

MatthewMartin
  • 32,326
  • 33
  • 105
  • 164
  • can you post your entire method contents. Also - `Contract.Ensures` must be the first line of code in any method. Code after your return statement will be unreachable.Thats why moving it there does nothing. – KP. May 21 '10 at 16:01

3 Answers3

6

I might be missing something, but I just looked at the documentation for this:

http://msdn.microsoft.com/en-us/library/dd412865.aspx

it says:

This method call must be at the beginning of a method or property, before any other code.

So just leave the Ensures call at the top of the method and you should not get any problems.

Jason Evans
  • 28,906
  • 14
  • 90
  • 154
3

It's pretty simple: the Contract class signals contract violations by throwing an exception. Putting it in a try block defeats the purpose, you're liable to catch the exception.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
2

Here's a similar solution:

http://social.msdn.microsoft.com/Forums/en/codecontracts/thread/43f467f1-14b7-4e56-8030-50f842b7ba68

Your recent edit shows you have code above the Contract.Ensures statement. Contract.Ensures must come before any other code in your method, so:

public object RetrieveById(int Id)
{    
    //first line of method:
    Contract.Ensures(newObject != null, "object must not be null");

    //stuff happens...

    return newProject;        
}
KP.
  • 13,218
  • 3
  • 40
  • 60