Skip to content

Nullable ref types: handling unconstrained type parameters #33436

@gafter

Description

@gafter

A variable of a type parameter that cannot be annotated, when read, may yield a null value. But a (possibly) null value cannot be stored in it, because the type may be substituted with a type that is non-nullable. If we apply the usual rules, that would mean this causes a diagnostic:

void M<T>(T t)
{
    t = t; // warning: might be assigning null to T
}

To solve this, we propose the following rules:

  1. The warning that a possibly-null value is converted to a type that doesn't accept null has an exception for a conversion to a value of a type that is a "type parameter that may possibly be a reference type and cannot be annotated" when the conversion is an implicit conversion (with two exceptions below). An implicit conversion to such an unannotatable type causes no warning. If the conversion is not implicit (e.g. a downcast between related type parameters) the warning is given.
  2. We must introduce a safety warning whenever a possibly null value of such a type is introduced. Those contexts are:
  • default and default(T) (the default conversion, though implicit, does introduce a warning)
  • null (the null conversion, though implicit, does introduce a warning)
  • e as T
  • e.GetFirstOrDefault() - which presumably would be annotated with [MaybeNull]

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions