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?
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With