Keith
Keith

Reputation: 155662

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?

Upvotes: 2

Views: 2076

Answers (1)

D M
D M

Reputation: 7179

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;
}

Upvotes: 2

Related Questions