C# 7.0 – Pattern Matching (JNNC Technologies)


In this article, we will discuss one of the planned language features in C# 7.0

In C# 7.0, two existing language constructs are enhanced with Patterns. those are Is-Expressions and Switch statements.
– is expressions
– case clauses in switch statements

Is Expressions with Patterns:

In the above example, the variables declared by the pattern is similar to Out Variables. You can read on out Variables here.

Pattern Variables can be declared in the middle of an expression, and can be used within the nearest surrounding scope. Also like out variables, pattern variables are mutable.

Switch Statements:


In C# 7.0,
– You can switch on any type (not just primitive types)
– Patterns can be used in case clauses
– Case clauses can have additional conditions on them

What is changed?

– The order of case clauses now matter
– The default clause is always evaluated last
– You can check null using case null syntax

Advantages:

– You can do pattern matching on any data type, even your own, whereas if/else you always need primitives to match
– Pattern matching can extract values from your expression

What to expect next?

– Microsoft has plan to add more patterns in future releases

0 Comments

'; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })();