How can I show that a method will never return nul

2020-08-18 08:36发布

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?

9条回答
乱世女痞
2楼-- · 2020-08-18 08:40

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

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.

查看更多
Root(大扎)
3楼-- · 2020-08-18 08:41

If your users have your source code using a standard design by contract API like: http://www.codeproject.com/KB/cs/designbycontract.aspx can make things clear.

Otherwise your best bet is through documentation.

查看更多
干净又极端
4楼-- · 2020-08-18 08:42

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.

查看更多
Root(大扎)
5楼-- · 2020-08-18 08:44

You could include a Debug.Assert() method. While this certainly won't enforce the condition, it should make it clear (along with documentation) that a null value isn't acceptable.

查看更多
Explosion°爆炸
6楼-- · 2020-08-18 08:47

I don't know that there is a best practice for doing so from an API as I would still program defensively and check for null as the consumer. I think that this is still the best practice in this case as I tend to not want to trust other code to always do the right thing.

查看更多
We Are One
7楼-- · 2020-08-18 08:49

The only type-checked way to ensure that a C# object never returns null is to use a struct. Structs can have members that contain null values, but can never be null themselves.

All other C# objects can be null.

Example code:

public struct StructExample
{
    public string Val;
}

public class MyClass
{
    private StructExamle example;

    public MyClass()
    {
        example = null; // will give you a 'Cannot convert to null error
    }

    public StructExample GetXyz()
    {
        return null; // also gives the same error
    }
}

The above example will not compile. If using a struct is acceptable (it becomes a value type, gets passed around on the stack, can't be subclassed) then this might work for you.

查看更多
登录 后发表回答