I am trying to wrap my head around .NET’s code contract. When using code contract, how do I log the assert causing the method in question to fail. For example, look at this code:
Public IsMatch(string x, string, y)
{
Contract.Assert(!string.IsNullOrWhiteSpace(x));
Contract.Assert(!String.IsNullOrWhitespace(y));
return x == y;
}
Let say x = string.Empty. This will cause the method to fail. How do I log that the assert cause the method above to fail. I can have many asserts such as this in a large app and it would be nice to know which one is the trouble-maker.
If you’re talking about logging, I assume you mean at runtime rather than static verification.
The asserts raise exceptions when they fail. You can write a try/catch block to log exceptions:
This will get you the stack trace of the exception, which will point to the line where the assertion failed.
As Polity mentioned, you can also include a
userMessageparameter on each assertion. That way your logs will contain custom error messages in addition to the stack trace.If you need a good
loggerclass, look at the NLog library.