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