C# 7.0 – Pattern Matching

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.

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

You can read more planned C#7.0 features here.

You can try this feature yourself using Visual Studio 15 Preview 4.

Thanks for visiting !! More On CSharp

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s