JetBrains Rider 2022.2 Help

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

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:

void Test(object obj) { var str = obj as string; if (str != null) { // do something } }
void Test(object obj) { if (obj is string str) { // do something } }
Last modified: 08 March 2021