Is and As can assign local variable to be used subsequently.
Is there a similar way to declare a local variable to be used after a null check?
if(Factory() != null factoryResult)
{
factoryResult.UsingResult();
}
Is and As can assign local variable to be used subsequently.
Is there a similar way to declare a local variable to be used after a null check?
if(Factory() != null factoryResult)
{
factoryResult.UsingResult();
}
Depending on which version of c#
you're using, it is possible to use pattern matching using is
keyword (is not
, if you want the opposite of what has been stated) to check not only for null
but also for specific properties, and declare in one go. You could also use the declared variable for additional checks in the same if
statement
As per your example, { }
would mean that it's an object of a class that is not null:
if(Factory() is { } factoryResult)
{
factoryResult.UsingResult();
}
or
if(Factory() is FactoryResult factoryResult)
{
factoryResult.UsingResult();
}
assuming that FactoryResult
is a class that is being returned from Factory()
or suppose you have to check also for IsUsable
boolean
that has to be true at the same time:
if(Factory() is FactoryResult { IsUsable: true } factoryResult)
{
factoryResult.UsingResult();
}