New C# 7 features in action: Pattern matching in C# 7 – switch statements with patterns

Switch statement with C# 7’s pattern matching enhancements

Switch on any type

Case clauses with patterns

Case clauses with additional conditions on them

Case clauses – order is important

Null clause – to handle null values

Default clause always evaluated last

Simple Credit Card Processor Class (used to explain C# 7’s switch statement enhancements)

Sample code to use C# 7’s pattern matching to enhance the switch statements

Note the use of pattern matching (in switch statement)

  1. Switch with object type (switch (creditCard))
  2. Case clauses with type patterns (case AmericanExpress amex:)
  3. Case clauses with additional conditions on them (case ICard card when card.IsValidCard == false:)
  4. Null clause – to handle null values (case null:)
  5. Case clauses – here order is important
  6. Default clause always evaluated last

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 *