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

[Nullable ref Types] Infer throw statements from extension methods #31642

Closed
garuma opened this issue Dec 8, 2018 · 2 comments
Closed

[Nullable ref Types] Infer throw statements from extension methods #31642

garuma opened this issue Dec 8, 2018 · 2 comments
Labels
Area-Compilers Feature - Nullable Reference Types Nullable Reference Types Resolution-Duplicate The described behavior is tracked in another issue

Comments

@garuma
Copy link

garuma commented Dec 8, 2018

Version Used: VisualStudio.16.int.d16.0stg/16.0.0-pre.2.0+28408.101.d16.0stg
C# Tools 2.11.0-beta2-63529-05+66aa49da81717aa54090a9e94c2f575ddb1959bb

Steps to Reproduce:

Simplified definition:

struct TwoEnumeratorListStack
{
    private readonly ArrayBuilder<Which>? _discriminatorStack;

    public Which PeekNext()
    {
        // Possible dereference of a null reference
        return _discriminatorStack[_discriminatorStack.Count - 1];
    }
}

To prevent the warning you can do:

public Which PeekNext()
{
    if (_discriminatorStack == null)
        throw new InvalidOperationException();
    return _discriminatorStack[_discriminatorStack.Count - 1];
}

Which removes the warning. However trying to capture the check in a general-purpose extension method:

internal static void ThrowInvalidIfNull<T>(this T? argument) where T : class
{
    if (argument == null)
        throw new InvalidOperationException();
}

public Which PeekNext()
{
    _discriminatorStack.ThrowInvalidIfNull();
    return _discriminatorStack[_discriminatorStack.Count - 1];
}

Doesn't remove the warning anymore and requires additional ! to both array indexer and .Count

@jaredpar
Copy link
Member

jaredpar commented Jan 2, 2019

Thanks for reporting! This scenario, and others, are covered in the following issue. The intent is definitely to support this

#32078

@jaredpar jaredpar closed this as completed Jan 2, 2019
@jaredpar jaredpar added the Resolution-Duplicate The described behavior is tracked in another issue label Jan 2, 2019
@jcouv
Copy link
Member

jcouv commented Jan 2, 2019

The [System.Runtime.CompilerServices.AssertsNotNull] attribute can be applied on the parameter of ThrowInvalidIfNull to help the compiler draw the correct inference.
You may have to define the attribute yourself for now, but we plan to add it to Core 3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Area-Compilers Feature - Nullable Reference Types Nullable Reference Types Resolution-Duplicate The described behavior is tracked in another issue
Projects
None yet
Development

No branches or pull requests

4 participants