Am I using
Contract.Requires
in the wrong way?
Yes, you are. Contract.Requires
is about stating preconditions for a method (or property). These are conditions that must be true for method invocation to proceed, otherwise you have a contract violation.
Let's take a look at your code:
var obj = Get<T>(id);
Contract.Requires<ArgumentNullException>(obj != null);
Here, you are trying to use it to ensure that something is true after a method has finished executing (in this case, the Get
method). That would be a postcondition and for that you would use Contract.Ensures
in the body of Get
:
protected T Get<T>(object id) {
Contract.Ensures(Contract.Results<T>() != null);
// get and return result
}
Lastly, this compiler error
After contract block, found use of local variable
obj
defined in contract block
This message is a result of the fact that you can not use Contract
s after the contract block, and the contract block appears at the top of body of a method only.