简体   繁体   中英

Visual Studio 2022 Intellisense null warning stays on with custom null validations

I have the following code on which I perform a custom type of null checking of my parameters. I do it that way to avoid writing 3 separate if statements (adds cyclomatic complexity) and in my opinion it just looks cleaner. However, VS2022, on.NET6 refuses to take away the null warning on the previously validated parameters.

Here's an example: I perform the custom null validation on all params and just do one manually (logger). Only the one done manually gets to be clean with no warnings. Any ideas how to make it work with custom null validations?

在此处输入图像描述

Compiler is not omnipotent and such semantical analysis is not that easy. If you care about cyclomatic complexity, cleanness, maintainability and correct nullable analysis flow, I would recommend to use ArgumentNullException.ThrowIfNull or to extract this functionality into separate method.

ArgumentNullException :

object x = null;
// Throws ArgumentNullException with message 
// Value cannot be null. (Parameter 'x')
ArgumentNullException.ThrowIfNull(x); 

If another exception type or message needed - extract custom method (can be local one, can be some helper):

class Guard
{
    public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression(nameof(argument))] string? paramName = null)
    {
        if (argument != null)
            return;
        throw new ArgumentException($"{paramName} can't be null");
    }

    public static void ThrowIfNull<T>([NotNull] T? argument, [CallerArgumentExpression(nameof(argument))] string? paramName = null) where T:struct
    {
        if (argument != null)
            return;
        throw new ArgumentException($"{paramName} can't be null");
    }
}

In .NET 6 the nullable reference types are enabled by default, this is why you are getting this warning. As mentioned in the comments, you can use null-forgiving operator to deliberately state that the value is not null and bypass this warning.

You could also disable the nullable types with the #nullable disable although it is not recommended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM