-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Description
No warnings are reported for the assignment to t in F1() or the explicit cast (T) in F2().
#nullable enable
class Program
{
static T F1<T>()
{
T t = default; // no warning
return t; // warning: possible null return
}
static T F2<T>(object? o)
{
T t = (T)o; // no warning
return t; // warning: possible null return
}
}For type parameters with constraints (or explicit types), the compiler reports warning CS8600: Converting null literal or possible null value to non-nullable type for those cases. The warning is not a safety warning because the compiler still tracks the "maybe default" state of the value and reports actual safety warnings when the values are used, as in the warnings reported for return t; above. But it is a difference in behavior between unconstrained type parameters and other types.
The reason the compiler does not report warnings for unconstrained type parameters is because in C#8 there is no syntax to specify the nullable version of the type parameter so any warning would require a ! suppression.
Post C#8, unconstrained type parameters can be annotated, so the code above could be replaced with the following. Given that, should the compiler report CS8600 for the cases above?
#nullable enable
class Program
{
static T F1<T>()
{
T? t = default; // ok
return t; // warning: possible null return
}
static T F2<T>(object? o)
{
T? t = (T?)o; // ok
return t; // warning: possible null return
}
}Metadata
Metadata
Assignees
Labels
Type
Projects
Status