Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DiagnosticsSuppress does not suppress CS8634 #462

Closed
manfred-brands opened this issue Jun 22, 2022 · 0 comments · Fixed by #554
Closed

DiagnosticsSuppress does not suppress CS8634 #462

manfred-brands opened this issue Jun 22, 2022 · 0 comments · Fixed by #554

Comments

@manfred-brands
Copy link
Member

Given the following constructed example:

[Test]
public void Test()
{
    object? possibleNull = GetNext();
    Assert.NotNull(possibleNull);
    DoNothing((object)possibleNull);
}

private static object? GetNext() => new object();

private void DoNothing<T>(T obj)
    where T : class
{}

Result in error:

CS8634 The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'TestClass.DoNothing<T>(T)'. Nullability of type argument 'object?' doesn't match 'class' constraint.

Even trying to be explicit, doesn't remove the error:

    object? possibleNull = GetNext();
    Assert.NotNull(possibleNull);
    object notNull = (object)possibleNull;
    DoNothing(notNull);

This might be a limitation on the DiagnosticSuppressors where we suppress the error generated for the cast, but we don't change the compiler's understanding of what could be null. We don't do a complete flow analysis on notNull

The only option that seems to work is by either using the null suppression operator: object notNull = possibleNull!;
or by doing the nullability conversion in a separate method:

[Test]
public void Test()
{
    object? possibleNull = GetNext();
    object notNull = EnsureNotNull(possibleNull);
    DoNothing(notNull);
}

private static object? GetNext() => new object();

private static object EnsureNotNull(object? possibleNull)
{
    Assert.NotNull(possibleNull);
    return (object)possibleNull;
}

private void DoNothing<T>(T obj)
    where T : class
{}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants