Search code examples
c#design-by-contract

How can I show that a method will never return null (Design by contract) in C#


I have a method which never returns a null object. I want to make it clear so that users of my API don't have to write code like this:

if(Getxyz() != null)
{
  // do stuff
}

How can I show this intent?


Solution

  • Unfortunately there is no way built in to C#

    You can document this fact, but this won't be automatically checked.

    If you are using resharper, then it can be set up to check this properly when the method is marked with a [NotNull] attribute.

    Otherwise you can use the Microsoft Contracts library and add something similar to the following to your method, but this is quite a lot of extra verbiage for such a simple annotation.

    Contract.Ensures(Contract.Result<string>() != null)
    

    Spec# solved this problem by allowing a ! after the type to mark it as a non-null type, eg

    string! foo
    

    but Spec# can only be used to target .NET2, and has been usurped by the Code Contracts library.