C# 7.0 and 7.1 support in ReSharper – Pattern matching with generics

ReSharper support for C# 7 and C# 7.1Pattern matching with generics (spec) is another great topic for our blog series about support for C# 7.0 and C# 7.1 in ReSharper (and Rider)! Using pattern matching, we can combine a type check with a cast, removing some language ceremony. Let’s see how ReSharper can help us with its inspections, quick-fixes and context actions.

In this series (we will update the table of contents as we progress):

Pattern matching with generics

C# 7.0 introduced pattern matching, and C# 7.1 adds pattern matching with generics. Using pattern matching, we can test whether a variable has a certain “shape” or type and then start working with it immediately, without having to use as + a null check. Here’s an example:

public void WhatIsThisThing(object data)
    if (data is null) return;
    if (data is int i) Console.WriteLine($"Integer: {i}");
    if (data is float f) Console.WriteLine($"Float: {f}");
    if (data is Person p) Console.WriteLine($"Person, with a name: {p.Name}");

Want to start making use of this language feature? ReSharper can spot when we are using “old style” use of as + a null check, and rewrite our code to use pattern matching.
ReSharper detects when to use pattern matching

ReSharper also adds a new context action: Generate type patterns. It lets us generate switch cases for selected types:
Generate type patterns - generates a switch case for pattern matching

Next to these, the Convert to switch quick-fix has been completely reworked to transform multiple if statements into a single switch statement with pattern matching:
Convert if/else statements to switch statement

Download ReSharper Ultimate or check out Rider that takes advantage of ReSharper’s language support updates. We’d love to hear your thoughts.

image description