Mike Walton
Mike Walton

Reputation: 4386

Non-nullable default return null warning

In C#8 we can now enable nullables, which means that reference types by default are considered not null by the compiler unless explicitly declared as nullable. Yet, it seems the compiler still throws a warning when trying to return a default generic with the notnull constraint. Consider the following example:

public TReturn TestMethod<TReturn>() where TReturn : notnull
{
    return default; // default is flagged with a compiler warning for possible null reference return
}

I thought maybe it would help if I also enforced that the return type must have an empty constructor, but it produces the same result:

public TReturn TestMethod<TReturn>() where TReturn : notnull, new()
{
    return default; // default is flagged with a compiler warning for possible null reference return
}

Why is the compiler flagging this line?

Upvotes: 2

Views: 352

Answers (1)

D Stanley
D Stanley

Reputation: 152624

TReturn : notnull means that TReturn must be a non-nullable type (which can be either a value type or a non-nullable reference type). Unfortunately, the value of default for non-nullable reference types is still null, hence the compiler warning.

If you want the "default" for a non-nullable reference type to be whatever is created with a parameterless constructor, for example, you could do:

public TReturn TestMethod<TReturn>() where TReturn : notnull, new()
{
    return new TReturn(); 
}

Upvotes: 2

Related Questions