No warning reported for assignment or explicit cast of possibly null value of unconstrained type parameter type
See original GitHub issueNo 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
}
}
Issue Analytics
- State:
- Created 3 years ago
- Comments:6 (6 by maintainers)
@RikkiGibson Yes, although it’s probably not a blocker (we could do it in a following warning wave)
If/when we decide to move ahead with investigation (what’s the impact on roslyn/VS/runtime), we should remember to let LDM know.