Background: There is this developer principle "Should my function return null or throw an exception if the requested item does not exist?" that I wouldn't like to discuss here. I decided to throw an exception for all cases that have to return a value and this value only wouldn't exist in cases of an (programmatically or logically) invalid reques开发者_开发知识库t.
And finally my question: Can I mark a function so that the compiler knows that it will never return null and warn anybody who checks if the return value is null?
You can do this using Code Contracts
.
Example :
public String Method1()
{
Contract.Ensures(Contract.Result<String>() != null);
// To do
}
Using Code Contracts you can define a contract that a method does not return null.
using System.Diagnostics.Contracts; // required namespace
public T MethodName()
{
Contract.Ensures(Contract.Result<T>() != null); //where T is the return type.
// method body...
}
You are looking for Code Contracts
If you return a value type, then it can't be null (unless you explicitly make it so using the system 'nullable' wrapper).
精彩评论