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?
new()does not mean "empty constructor"defaultstill meansnullfor reference types.defaultwill always returnnullfor classes. It won’t attempt to construct a new instance, even if there’s a default constructor.new()constraint in place, you could instead callreturn new TReturn().