There are two obvious benefits:
(1) The code is much easier to read.
Contract.Requires(someParam != null && someParam.SomeValue != 0);
versus
if (someParam != null && someParam.SomeValue != 0)
throw new ArgumentNullException("someParam", someParam, "someParam can't be null and someParam.SomeValue can't be zero.");
Also, with Code Contracts, the predicate code is automatically put into the failure message so you don't need to write an explicit message like you do with normal exceptions.
(2) You can run Code Contracts static analysis on the code and it can find errors for you.
There are some less obvious benefits:
(3) You can generate documentation for the code contracts in the XML doc files.
(4) You can use Contract.Ensures()
to express postconditional constraints. This allows you to avoid a lot of code like if (item.Property1 != null && item.Property1.Property2 != null) ...
because you will know that neither Property
or Property2
can be null.
(5) The code contracts form a block that is clearly separate from the rest of the code.