Code Analysis Code Analysis
Code Analysis Code Analysis
DocFX + Singulink = ♥

Search Results for

    SCA1047: NotNullRef on a Method of the Project

    Verify a method with a [NotNullRef] parameter, then suppress this warning on it.

    Example

    internal static class Ensure
    {
    #pragma warning disable SCA1047 // Verified and tested: it throws for a null reference and does nothing else
        public static void RefersToSomething<T>(
            [NotNullRef] ref readonly T reference,
            [CallerArgumentExpression(nameof(reference))] string? expression = null)
        {
            if (Unsafe.IsNullRef(in reference))
                Throw(expression);
    
            static void Throw(string? expression) => throw new NullReferenceException($"The reference '{expression}' is a null reference.");
        }
    #pragma warning restore SCA1047
    }
    

    How to Fix

    Verify and test the method, then suppress the warning there, with a #pragma or a [SuppressMessage] that says so.

    Details

    A parameter that the project declares is marked [NotNullRef] where the mark counts. The analyzer does not check that the method returns only if the reference that it is given refers to something. The analyzer's warnings for a [MovedFrom] parameter and for a commit at the end of a try block rely on that promise.

    • You get this warning once for each mark, where the attribute stands.
    • You do not get it for a method of a referenced assembly, such as the two checks in the attributes package.
    • It has an ID of its own, so that you can suppress it and still get SCA1046.

    See Also

    These articles explain the rule behind this warning:

    • Null References - references that are known to refer to something, and the NotNullRef mark.
    © Singulink. All rights reserved.