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);
}
}
}
As dotnet/csharplang#2814 describes, just put [NotNull] on object argument.
Most helpful comment
As dotnet/csharplang#2814 describes, just put
[NotNull]onobject argument.