We at d-fens use Microsoft Code Contracts every day. And certainly with every great tool there are some things that might benefit from some improvement – and code contracts are […]
We at d-fens use Microsoft Code Contracts every day. And certainly with every great tool there are some things that might benefit from some improvement – and code contracts are no exception. There is one particular annoying thing in that the error message for Contract.Result exceptions strips the generic parameters from it. This in essence means, that every time we get a post condition failure from a null check like Contract.Ensures(null != Contract.Result()) we end up with an error message like this:
Postcondition failed: null != Contract.Result()
As the type Permission is left out, we cannot really tell by the message what actually has been null. Luckily, there is an easy workaround for this: by defining a constant default(Permission) variable we can use this for our null check:
As we are using contract messages as error messages in our API code, we now can easily create more meaningful error messages without resorting to custom messages: