New C# 7.0 Features. Pattern Matching

C# 7.0 Pattern MatchingGreat news! You can already try new C# 7.0 features. All you need is Visual Studio 15 Preview. Let’s start!

Today we are going to talk about Pattern Matching and will look under the hood of this nice feature. Unfortunately, it is only partly available in VS 15. So we need to wait until next release. Or you can try to get latest Roslyn from GitHub.

is operator

The is operator is extended to test an expression against a pattern.

With that you can replace this:

With shorter (and safer) version:

It is safer because str variable is visible only in the if scope

Produced IL code is identical:

You can also use pattern matching to match value type:

But you should be aware that internally it will be unboxed to Nullable<T> type. Here is IL code:

It is equivalent to following C# code:

Even though it is unboxed to Nullable<int> type, in if scope you will have num variable of System.Int type.

You can also use var in pattern matching. A match to the var pattern is always succeeded.

As well as * pattern:

There is constant pattern match:

Which will be replaced with call to the object.Equals method

Unfortunately, User-defined operator is is not implemented yet. So recursive pattern matching is not working.

That’s it for today. In the next part, we will talk about pattern matching in switch statement:

Leave a Reply

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