I’ve already talked about the simple contract checking library here. I did a little improvement that allow us to write such a code:
public void DoSomethingWithCustomMessage(string arg1)
{
Contract.Expect(() => arg1)
.Throw<Exception>("I'm unhappy to see that {0} is null")
.WhenViolate
.IsNotNull();
}
Note than {0} is replaced with the name of the argument so the library is refactoring friendly and DRY. The only restriction is that the exception type must support a constructor with a single string argument. Obviously .Throw can be used fluently after each all Expect(). As another minor improvement, even the .Expect can be called now fluently more than once, so multiple check can be done fluently too. The entire repository is on Bitbucket here. In order to use the library you just have to include the single file, but is better to point the repository since the file version can change in subsequent releases.