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

public static bool DoPayment(object creditCard, decimal amount)
{
	switch (creditCard) // // Switch on any type, here creditCard is of type object
	{
	  // Some code.
	}
}

Case clauses with patterns

switch (creditCard) // Switch on any type, here creditCard is of type object
{
	
	case AmericanExpress amex: // Case clauses with type pattern "AmericanExpress amex" 
		{
			success = amex.ProcessAmexPayment(amount);
			break;
		}
		
}

Case clauses with additional conditions on them

switch (creditCard) // Switch on any type, here creditCard is of type object
{
	case ICard card when card.IsValidCard == false: // Case clauses with type pattern "ICard card" and additional conditions
		{
			success = false;
			break;
		}
		
}

Case clauses – order is important

switch (creditCard) // Switch on any type, here creditCard is of type object
{

	case Visa visa when visa.IsCreditCard == false: // Evaluate before "case Visa visaCreditCard"
		{
			success = visa.ProcessVisaPayment(amount);
			break;
		}

	case Visa visaCreditCard:
		{
			success = visaCreditCard.ProcessVisaCreditCardPayment(amount);
			break;
		}
}

Null clause – to handle null values

switch (creditCard) // Switch on any type, here creditCard is of type object
{

	 case null: // Null clause - to handle null values
		{
			success = false;
			// Code to handle null values 
			break;
		}
}

Default clause always evaluated last

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

using System;

namespace SampleApplication
{
    public interface ICard
    {
        bool IsValidCard { get; set; }
    }

    public class AmericanExpress : ICard
    {
        public bool IsValidCard { get; set; }

        public bool ProcessAmexPayment(decimal amount)
        {
            throw new NotImplementedException();
        }
    }

    public class Visa : ICard
    {
        public bool IsValidCard { get; set; }

        public bool IsCreditCard { get; set; }
         
        public bool ProcessVisaPayment(decimal amount)
        {
            throw new NotImplementedException();
        }

        public bool ProcessVisaCreditCardPayment(decimal amount)
        {
            throw new NotImplementedException();
        }
    }

    public class MasterCard : ICard
    {
        public bool IsValidCard { get; set; }

        public bool IsCreditCard { get; set; }

        public bool ProcessMasterCardPayment(decimal amount)
        {
            throw new NotImplementedException();
        }

        public bool ProcessMasterCreditCardPayment(decimal amount)
        {
            throw new NotImplementedException();
        }
    }
}

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:

namespace SampleApplication.CSharp7
{
    public partial class CSharp7Sample
    {
        public static bool DoPayment(object creditCard, decimal amount)
        {
            if (amount == 0)
            {
                return false;
            }

            bool success = false;

            switch (creditCard) // Switch on any type, here creditCard is of type object
            {
                case ICard card when card.IsValidCard == false: // Case clauses with type pattern "ICard card" and additional conditions
                    {
                        success = false;
                        break;
                    }

                case AmericanExpress amex: // Case clauses with type pattern "AmericanExpress amex" 
                    {
                        success = amex.ProcessAmexPayment(amount);
                        break;
                    }

                case Visa visa when visa.IsCreditCard == false:
                    {
                        success = visa.ProcessVisaPayment(amount);
                        break;
                    }

                case Visa visaCreditCard:
                    {
                        success = visaCreditCard.ProcessVisaCreditCardPayment(amount);
                        break;
                    }

                case MasterCard masterCard when masterCard.IsCreditCard == false:
                    {
                        success = masterCard.ProcessMasterCardPayment(amount);
                        break;
                    }

                case MasterCard masterCreditCard:
                    {
                        success = masterCreditCard.ProcessMasterCreditCardPayment(amount);
                        break;
                    }

                case null: // Null clause - to handle null values
                    {
                        success = false;
                        // Code to handle null values 
                        break;
                    }

                default: // Default clause always evaluated last
                    {
                        success = false;
                        break;
                    }
            }

            return success;
        }
    }
}

Happy Coding !!!

You may also like...

2 Responses

  1. scrapbook sequin glitter says:

    I’m really enjoying the design and layout of your website.
    It’s a very easy on the eyes which makes iit much more pleasant for me to come here and visit mopre often. Did you
    hire out a designer to create your theme? Fantastic work!

  2. C# Switch on Type says:

    This is a great explanation of pattern matching and how to switch on types in C#. Thank you for sharing. Cheers!

Leave a Reply

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