Code Contracts are a relatively new way of performing checks on input and output of functions. Where they differ from your standard Assert
type checking is that the generated IL that checks input checks it directly prior to the function being called, and the code that checks output, after your function has actually exited.
Why is this useful?
Well, it prevents you modifying the variables after you think your function may return, thereby potentially introducing bugs.
Here's an example.
public void doSomething(SomeObject foo)
{
Contract.Requires<ArgumentNullException>(foo != null);
}
Now, Code Contracts require that there be no code before that check. In the generated IL, the value of foo
is tested PRIOR to the call. It's a sure-fire way of ensuring that your input is as expected.
The other, is the Contract.Ensures
construct. This is basically like Requires
but operates on your return value.
public int doSomethingElse()
{
Contract.Ensures(Contract.Result<int>() != 0);
int ret = 1;
return ret;
}
This would be particularly useful if you had multiple exit paths from your function...
public int someBadFunction()
{
Contract.Ensures(Contract.Result<int>() != 0);
if(....)
{
if(....) return 2;
if(....) return 8;
}
return 3;
}