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:

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.

About Maarten Balliauw

Maarten Balliauw is a Developer Advocate at JetBrains, working on .NET tools and Space. He focuses on .NET, Azure, web technologies and application performance. Maarten is a frequent speaker at various national and international events. In his free time, he brews his own beer. Follow him on Twitter or check out his personal blog.
This entry was posted in How-To's and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *