5

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?
}
3
  • Is this a question about the functional background of var and why this even compiles or don't you understand what var does in general? To say it simple: var is a shotcut for a definition, where the compiler will derive the type itself during compilation. var itself is a strong type, meaning it cannot change during runtime. Commented Jun 18, 2021 at 11:31
  • var is not a real type. It is used to tell the C# compiler it can just use the compile-time type of the expression being assign as the variable type for the variable being declared. So how should it be determined if expr is var? It makes no sense, does it? Commented Jun 18, 2021 at 11:31
  • @ChrᴉzsupportsMonica: No, it's not really about that - it's about using var in pattern matching. Commented Jun 18, 2021 at 11:31

1 Answer 1

13

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Will the expression under if always evaluate to true?
@JeppeStigNielsen: Yes, I believe so - in this case, anyway. I'm going to check for another possible case...
It would be a nice "line-saver"
@Wouter: I think I've got an alternative - just checking now.
It seems crazy not to write { var bar = foo.GetBar(); bar.Baz(); }.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.