Really trying to like CodeContracts in C#

Solution 1:

This feels like such a cludge to me, I wish there was a cleaner way to document requirements, either via attributes or some form of built in language support.

The CC team have stated that using Attributes just isn't powerful enough, because you can't include things like lambdas in them. They could include things like [NotNull] but have chosen not to do so because they're trying to keep CC as general as possible.

One reason that CC is a library (rather than part of an extended C#) is that it is supported across all .NET languages.

You can read more about the team's reasoning here.

In terms of actually using this, so far I've just been keeping my interface contracts in the same file as the interface, which means it's all documented in the same place. It is something that should be improved upon :)

Code Bloat [...]

Your second complaint is probably something that can be implemented -- I'd suggest posting it on the code contracts forum. (EDIT: Seems someone already has, but no answers yet.)

However, it will always be the case that under-specified contracts will need more assumptions surrounding them. If you run into a case like this in the .NET framework you can request that contracts be added in the Missing Contracts on Libraries thread.

In addition, taking a case like [...]

This has been addressed. If you have an auto-property, you just have to add an non-null invariant and the pre-/post-conditions will be generated:

public class MyClass : IInterface
{
    private Object Property { get; set; }

    [ContractInvariantMethod]
    private void Invariants()
    {
        Contract.Invariant(Property != null);
    }
}

You'll probably end up with other invariants for your classes anyway, so it's not that big a deal.

Solution 2:

Yeah, contracts clutter things up, but I feel like it's worth it when PEX reads the code contracts and generates 25 unit tests and 100% code coverage for me. If you haven't used PEX yet, then you're missing out on the biggest benefit of code contracts. Here's a starter guide for using PEX with contracts.