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?
}
varand why this even compiles or don't you understand whatvardoes in general? To say it simple:varis a shotcut for a definition, where the compiler will derive the type itself during compilation.varitself is a strong type, meaning it cannot change during runtime.varis 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 ifexpr is var? It makes no sense, does it?varin pattern matching.