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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.
Spec# solved this problem by allowing a ! after the type to mark it as a non-null type, eg
but Spec# can only be used to target .NET2, and has been usurped by the Code Contracts library.