Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 563
StackUnderflow Avatar asked Jan 27 '09 18:01

StackUnderflow


2 Answers

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][1] 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. [1]: http://research.microsoft.com/en-us/projects/contracts/

like image 119
Oliver Hallam Avatar answered Sep 21 '22 14:09

Oliver Hallam


Unless you are using a type based on System.ValueType, I think you are out of luck. Its probably best to document this clearly in the XML/metadata comment for the function.

like image 39
Jason Jackson Avatar answered Sep 19 '22 14:09

Jason Jackson