Given:
public class Foo
{
public Bar GetBar() => null;
}
public abstract class Bar
{
public abstract void Baz();
}
This works:
var foo = new Foo();
var bar = foo.GetBar();
if (bar != null)
{
bar.Baz();
}
and this works also:
var foo = new Foo();
if (foo.GetBar() is Bar bar)
{
bar.Baz();
}
But why doesn't using var in the if statement work?
This compiles but can throw a null reference exception:
if (foo.GetBar() is var bar)
{
bar.Baz(); // <-- bar can still be null?
}
The var
pattern does match null values, whereas a type pattern doesn't - that's all there is to it, really.
From the reference docs (emphasis mine):
Beginning with C# 7.0, you use a
var
pattern to match any expression, including null, and assign its result to a new local variableA
var
pattern is useful when you need a temporary variable within aBoolean
expression to hold the result of intermediate calculations. You can also use avar
pattern when you need to perform additional checks in when case guards of a switch expression or statement
You can use a trivial property pattern as an alternative though:
var foo = new Foo();
if (foo.GetBar() is {} bar)
{
bar.Baz();
}
Here the {}
is a property pattern which matches any non-null value, but bar
is still typed as if via var
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With