Wouter
Wouter

Reputation: 2938

Using var in an if statement

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

Upvotes: 5

Views: 798

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499900

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.

Upvotes: 13

Related Questions