Roslyn: implementing a nullable guard method

Created on 24 Oct 2019  路  1Comment  路  Source: dotnet/roslyn

Is there any way I can write the guard method Guard.ThrowIfNotNull for the example below so that the compiler warning CS8602 goes away?

public void SomeMethod(object? someArgument)
{
    Guard.ThrowIfNotNull(nameof(someArgument), someArgument);
    Console.WriteLine(someArgument.ToString()); // CS8602: Dereference of a possibly null reference.
}

For reference, this is what I could write for the ReSharper/Rider code analysis. I could use the attribute [ContractAnnotation("halt <= argument:null")] to tell the analyzer that the guard method will not return if its argument named argument is null.

internal static class Guard
{
    // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Global
    [DebuggerStepThrough]
    [ContractAnnotation("halt <= argument:null")]
    public static void ThrowIfArgumentNull([InvokerParameterName] string argumentName, object argument)
    {
        if (argument == null)
        {
            throw new ArgumentNullException(argumentName);
        }
    }
}
Area-Compilers New Language Feature - Nullable Reference Types Question Resolution-Answered

Most helpful comment

As dotnet/csharplang#2814 describes, just put [NotNull] on object argument.

>All comments

As dotnet/csharplang#2814 describes, just put [NotNull] on object argument.

Was this page helpful?
0 / 5 - 0 ratings