Today I discovered a nifty use for code contracts: logging return values (even when a method has multiple return points).

I was running NUnit tests which were failing because of contract violations. The trouble is, the exception that was raised was showing which Contract.Ensures() failed, but not the return value that caused the problem.

I hacked up the following temporary solution that uses a fake test to log the results, calling it before the other post-conditions. I was then able to see the return value that was causing the problem – it was the last value printed to the log (and so visible from a tab in NUnit).

public double SomeMethod()
{
    Contract.Ensures(PrintResult(Contract.Result<double>())); // HACK
    Contract.Ensures(0 < Contract.Result<double>());
}

[Pure]
private static bool PrintResult(object result)
{
    Console.WriteLine(result);
    return true;
}