Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using var in an if statement

Tags:

c#

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?
}
like image 672
Wouter Avatar asked Jun 18 '21 11:06

Wouter


1 Answers

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 variable

A var pattern is useful when you need a temporary variable within a Boolean expression to hold the result of intermediate calculations. You can also use a var 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.

like image 150
Jon Skeet Avatar answered Sep 27 '22 19:09

Jon Skeet