[EN] New features in C# 7.0: out variables, pattern matching

Some time ago I wrote about new features in C# 6.0 and now it’s time to look at the features in C# 7.0 and what news it introduces. In this post I want to focus on out variables and pattern matching.

Out variables

In C# 7.0 we can declare a variable at the point it is passed as an out argument. I have created OutVariables class which contains sample methods implementation to demonstrate how out variables work. To have better view what it simplifies here we have two methods, one is in C# 6.0 (Cs6Style) and the second one is with C# 7.0 (Cs7Style).

Pattern matching

Pattern matching is another feature. In C# 7.0 we can use patterns only in is expressions and in case clausules for now, but it will be extended in the future versions of C#. Let’s take a look at the samples below.

Here we have SampleClass and two methods. Cs7Is method presents how to use is pattern and Cs7Case method presents how to use case pattern.
As you can see using is pattern is similar to the out variables, we can declare variable in the expression and use it later.
Case pattern allows us to extend switch statement. We can switch on any type, not only primitives. We can use patterns in case clausules and these clausules can have additional conditions.
That’s it for today, in the next posts we will take a look at the other features in C# 7.0.

 

One comment

  1. I’m not quite sure why it’s called pattern matching. It looks more like guards to me („when” statements; „is” does not seem like pattern matching at all). But nice addition anyway.

Comments are closed.