JetBrains Rider
 
Get JetBrains Rider
Get your hands on the new features ahead of the release by joining the Early Access Program for Rider 2025.1! Learn more

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

Last modified: 08 April 2024

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. JetBrains Rider will detect these patterns in your code and help to convert them into a more elegant pattern matching form. For example: