简体   繁体   中英

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM