开发者

C#: Declare that a function will never return null?

开发者 https://www.devze.com 2023-01-28 07:54 出处:网络
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 a

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).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号