Search code examples
c#.netcode-contracts

Code contracts static checks for reference types and null reference


Is that true that Code Contracts static analysis cannot check the explicit return new ... in a single branch methods (methods that don't have any conditionals and have only one return) like:

static public Tuple<int> Foo()
{
    return new Tuple<int>(42);
}

still warns me with

warning : CodeContracts: Possibly calling a method on a null reference. Do you expect that SomeClassName.Foo() returns non-null?

I indeed can help a static checker with

Contract.Ensures(Contract.Result<Tuple<int>>() != null);

explicitly but it looks like a huge overhead.

So my question is: am I missing something or that's my obligation to Ensure even such a trivial cases?


Solution

  • When calling out to other methods, code contracts relies on what has been explicitly stated. As you are suggesting, it could probably work this out in some cases but in general, do you really want it to? For a trivial example like this, it does make sense, but in general, just because a method currently doesn't return null that doesn't mean that the author is explicitly guaranteeing that.

    This is where the contracts come in, rather than just describing what the code does, it is describing what you are guaranteeing the code will do which is a slightly different thing. So to answer your question, yes, even though it is a bit of an overhead for trivial cases, it is you have to Ensure these trivial cases.