ReSharper
 
Get ReSharper
You are viewing the documentation for an earlier version of ReSharper.

Code Inspection: Convert 'as' expression type check and the following null check into pattern matching

Last modified: 21 July 2022

Starting with C# 7.0, we can combine type check, null check, and type cast using pattern matching in the following form: Expression is Type variable — if Expression is not null and assignable to Type, then it will be assigned to variable, otherwise the pattern will return false.

Before C# 7.0, the most widespread pattern to do so was to safe cast the expression using as, and then check for the variable null. ReSharper will detect these patterns in your code and help to convert them into a more elegant pattern matching form. For example: