Skip to content

No warning reported for assignment or explicit cast of possibly null value of unconstrained type parameter type #46044

@cston

Description

@cston

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

Type

No type

Projects

Status

Language/design

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions