简体   繁体   中英

C# nullable check verify that property is not null

I have a complex object I want to check is valid. I have a method to check it, but C# nullability checks don't know about them:

#nullable enable
...

bool IsValid(Thing? thing) 
{
    return thing?.foo != null && thing?.bar != null;
}

...

if(IsValid(thing)) 
{
   thing.foo.subProperty; // CS8602 warning: foo is possibly null here

Is there any way to apply something like TypeScript's type-gates here? If IsValid is true then we know that thing.foo is not null, but the C# analyser can't see inside the function. If I inline the check it can, but then I'm copy-pasting code and this is a simple example.

Is there any annotation or pattern where I can have the nullability analysis with the more complex checks?

You can use the null-forgiving operator like this:

if (IsValid(thing))
{
    thing.foo!.subProperty;
}

As @JeroenMostert points out, while it won't help you with foo , an alternative is the NotNullWhen attribute.

The compiler knows thing is not null here, but foo might still be null .

bool IsValid([NotNullWhen(true)] Thing? thing)
{
    return thing?.foo != null && thing?.bar != null;
}

if (IsValid(thing))
{
    thing.foo;
}

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