89
90 object o = new Foo();
91 var foo = o as Foo;
92 if (foo != null) 93 {
94 //
95 }
Comparing the result of the as
expression with null
allows you to check if the conversion operation was successful or not. However, it can be rewritten using the is
operator allowing you to collapse the cast operation and the result check, thereby making your code concise and naturally readable.
var foo = mayBeFoo as Foo;
if (foo == null)
{
// `foo` is not of type `Foo`
}
// Do something with `foo`
if (mayBeFoo is not Foo foo)
{
// `foo` is not of type `Foo`
}
// Do something with `foo`