C# 8 gives a warning when returning a nullable generic with nullable constraint

一世执手 提交于 2020-01-11 14:41:07

问题


This code:

public T Foo<T>()
    where T : class?
{
    return null;
}

Gives a following error:

A null literal introduces a null value when 'T' is a non-nullable reference type

I don't see why we can't return null when we say that T can be nullable. If we additionally try to return T? we will get an error that T has to be non-nullable.

It seems it's kind of impossible to have a nullable constraint and return a nullable result at the same time.


回答1:


Imagine you call:

string result = Foo<string>();

result now contains null. But it's a string, which is not nullable.

The compiler is warning you that Foo<T> may be called where T is not nullable, and returning null in this case would be unexpected.

Note that where T : class? means that T may be nullable, but it also might not be. Both string and string? are allowed. I don't believe there's any way to say "T must be nullable".


If you're trying to say:

  1. T is allowed to be nullable
  2. When T is non-nullable, then this type can still return null

Then you can write:

[return: MaybeNull]
public T Foo<T>()
    where T : class?
{
    return null!;
}

SharpLab

Note that MaybeNull only applies to the method's contract and not its body, when is why we need to return null!. However you can see in the SharpLab link above that the caller string result = Foo<string>(); gets the correct warning.




回答2:


Let's start from basic. Let say you have a reference type variable that allows it to have null value. But your program design requires it to be not null all times, if a null value is encountered, it is mostly likely to get the NullReferenceException.

To avoid such design issues, The NullableReference types was introduced. Means if a reference type is allowed to have null you should mark it as Nullable and any usage should check for null value before using it. If checking is not found then compiler will generate a warning.

If you read this introductory article on NullableReferenceTypes You will get the fair idea of what is the intent of this new feature.



来源:https://stackoverflow.com/questions/59631460/c-sharp-8-gives-a-warning-when-returning-a-nullable-generic-with-nullable-constr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!