roslyn
roslyn copied to clipboard
"A nullable type parameter must be known to be a value type or non-nullable reference type" on type parameter with `notnull` constraint
Version Used: C# 9 preview as of Visual Studio 2019 Preview 16.7 preview 4.0.
Steps to Reproduce: Here's an example instead.
public bool TryGetComponent<T>([NotNullWhen(true)] out T? component) where T : notnull // [at `T?`] CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type. Consider adding a 'class', 'struct', or type constraint.
{
if (TryGetComponent(component => component is T, out object? foundComponent))
{
component = (T)foundComponent;
return true;
}
else
{
component = null; // CS0403: Cannot convert null to type parameter 'T' because it could be a non-nullable value type. Consider using 'default(T)' instead.
return false;
}
}
Expected Behavior: The compiler detects that T
has the notnull
constraint and doesn't emit the errors:
- CS8627 on the
component
parameter — from my understanding, theclass
/struct
knowledge must exist purely because of nullability, but that's already defined as "not allowed" by thenotnull
constraint. - CS0403 on
component = null
— the variable in question is of a nullable type. It could be that this error is due to the previous one.
Actual Behavior:
- The compiler emits errors for both of the scenarios above.
I know of two solutions, but neither are suitable for me:
- The
[MaybeNull]
attribute — other nullable warnings will be emitted at call sites if the type itself is not nullable, for reasons irrelevant to this issue. - Adding the
class
orstruct
constraint — I need both to be usable with a single method.
Does this bug still exist in VS 2022? I don't get the [at 'T?'] CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type. Consider adding a 'class', 'struct', or type constraint.
error anymore.