New C# 7 features in action: Pattern matching in C# 7 – Is expressions with patterns

Patterns in C# 7.0

Constant patterns (c): checks that the input is equal to constant expression

Type patterns (T x): checks that the input is of type T, and if it is, then extracts the value of the input into a new variable x of type T

Var patterns (var x): puts the value of the input into a new variable x with the same type as the input

In C# 7,  pattern matching is introduced to enhance:

  • is expressions
  • switch statements

Is expression with C# 7’s pattern matching enhancements

Simple Credit Card Processor Class

Before C# 7: Sample code to explain the use of is expression in older versions of C#

Modifications to the above sample code to use C# 7’s pattern matching to enhance the is expression

Note the use of pattern matching (in is expression)

  1. constant pattern
  2. type pattern
  3. type pattern with condition

in the below sample code:

Happy Coding !!!

Kapil Khandelwal

Web Developer, Blogger, Microsoft Certified Professional (MCP), DZone's Most Valuable Blogger (MVB)

You may also like...

Leave a Reply

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