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).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class OutVariables { public void Cs6Style() { int a, b; TestMethod(out a, out b); Console.WriteLine($"a = {a} \t b = {b} "); } public void Cs7Style() { TestMethod(out int a, out int b); TestMethod(out var c, out var d); TestMethod(out _, out _); //I don't care about out variables Console.WriteLine($"a = {a} \t b = {b} "); Console.WriteLine($"c = {c} \t d = {d} "); } public void TestMethod(out int a, out int b) { a = 11; b = 22; } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
class SampleClass { public int Id { get; set; } } private void Cs7Is() { object c1 = new SampleClass() { Id = 1 }; if (c1 is SampleClass c) { Console.WriteLine(c.Id); } } private void Cs7Case() { object c1 = new SampleClass() { Id = 2 }; switch (c1) { case SampleClass sc when sc.Id % 2 == 0: Console.WriteLine("Id % 2 == 0"); break; case SampleClass sc: Console.WriteLine(sc.Id); break; case null: Console.WriteLine("Obj is null"); break; default: Console.WriteLine("Nothing to do"); break; } } |
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.