New C# 7 Features - Is Expression With Patterns And Switch Statement With Patterns - Part Two

This article explains new C# 7.0  features that make developers' lives easy, including Is Expression with Patterns and Switch statement with Patterns. Let's explore these features one-by-one with a small example which will help us to understand easily. 

Is Expression with Patterns

This is an expression that allows us to add a pattern on the right side of the expression, that can be a value extracted from an expression. In the below code snippet I have added pattern emp, which will extract value from the expression and we can get values like emp.firstName and emp.lastName.
  1. class Program      
  2.     {      
  3.         static void Main(string[] args)      
  4.         {      
  5.             var fulllTimeEmployee = new FullTimeEmployee()      
  6.             {      
  7.                 employeeId = 100001,      
  8.                 firstName = "Jingeh",      
  9.                 lastName = "Kumar",      
  10.                 anualSalary = 5000000      
  11.             };      
  12.       
  13.             var contractEmployee = new FullTimeEmployee()      
  14.             {      
  15.                 employeeId = 100002,      
  16.                 firstName = "Abhilash",      
  17.                 lastName = "Pandey",      
  18.                 anualSalary = 4500000      
  19.             };      
  20.       
  21.             // Is expression Pattern In C# 7.0      
  22.             if (fulllTimeEmployee is Employee emp)      
  23.                 Console.WriteLine($"This employee is {emp.firstName} + {emp.lastName} full time Empliyee");      
  24.             else      
  25.                 Console.WriteLine("This employee is not full time employee");      
  26.         }      
  27.       
  28.     }      
  29.     public abstract class Employee      
  30.     {      
  31.         public int employeeId;      
  32.         public string firstName;      
  33.         public string lastName;      
  34.         public abstract double CalculateSalary();      
  35.     }      
  36.     public class FullTimeEmployee : Employee      
  37.     {      
  38.         public int anualSalary { getset; }      
  39.         public override double CalculateSalary()      
  40.         {      
  41.             return this.anualSalary / 12;      
  42.         }      
  43.     }      
  44.       
  45.     public class ContractEmpoyee : Employee      
  46.     {      
  47.         public int hourlyRate { getset; }      
  48.         public int totalHours { getset; }      
  49.       
  50.         public override double CalculateSalary()      
  51.         {      
  52.             return this.hourlyRate * this.totalHours;      
  53.         }      
  54.     }      

Switch statement with Patterns 

In the context of pattern matching, the switch case statement pattern enhances the case blocks by allowing us to compare the value of switch with the value returned by an expression, rather than a fixed value.

Before the C# 7.0  switch statement. we had to define a specific value and then we had our case statements. To demonstrate this in our current scenario we have a class for a performer, actor, and a dancer.

The below code snippet is for the switch statement in C# 7.0  
  1. class Program        
  2.    {        
  3.        static void Main(string[] args)        
  4.        {        
  5.            Performer p = new Performer();        
  6.            Dancer d = new Dancer()        
  7.            {        
  8.                Name = "Michle",        
  9.                Age = 30,        
  10.                Gender = "Male",        
  11.                BestDance = "BestDance"        
  12.            };        
  13.            Actor a = new Actor()        
  14.            {        
  15.                Name = "Tom peter",        
  16.                Age = 35,        
  17.                Gender = "Male",        
  18.                BestAward = "FilmFare",        
  19.                BestMove = "Harry Potter"        
  20.            };        
  21.         
  22.            // Switch Statement in C# 7        
  23.            switch (a)        
  24.            {        
  25.                case Performer performer when (performer.Age == 40):        
  26.                    Console.WriteLine($"The performer {performer.Name}");        
  27.                    break;        
  28.                case Actor actor when (actor.Age == 35):        
  29.                    Console.WriteLine($"The Actor name is {actor.Name}");        
  30.                    break;        
  31.                case Actor actor:        
  32.                    Console.WriteLine($"The Actor is unknown");        
  33.                    break;        
  34.                default:        
  35.                    Console.WriteLine("Not found");        
  36.                    break;        
  37.                case null:        
  38.                    throw new ArgumentNullException(nameof(a));        
  39.            }        
  40.            Console.ReadLine();        
  41.        }        
  42.    }        
  43.    public class Performer        
  44.    {        
  45.        public string Name { getset; }        
  46.        public int Age { getset; }        
  47.        public string Gender { getset; }        
  48.    }        
  49.    public class Dancer : Performer        
  50.    {        
  51.        public string BestDance { getset; }        
  52.        public int Year { getset; }        
  53.    }        
  54.         
  55.    public class Actor : Performer        
  56.    {        
  57.        public string BestMove { getset; }        
  58.        public string BestAward { getset; }        
  59.    }        
Now, you can apply switch on any type. Here we have passed Actor object to switch statement.
  1. Actor a = new Actor();      
  2. switch (a)        
  3. {      
  4.   // Case blocks     
  5.   // Case blocks     
  6. }      

Case clause with pattern & additional condition on them

Here, we have checked additional condition using when clause, based on age. If age is equal to 40 then this case clause executes.
  1. switch (a)        
  2. {        
  3.      case Performer performer when (performer.Age == 40):        
  4.           Console.WriteLine($"The performer {performer.Name}");        
  5.           break;        
  6.                     
  7.  }   

Default clause and null check

Here are two things to notice while working with the switch statement.

Null case is not unreachable, so don't think that we just step down case by case and hit default and then it never hits null case. If you want to check null condition in the below example then try to pass Actor object as null above switch.

Default clause is always evaluated last.

  1. Actor a = null;    
  2. switch (a)          
  3. {          
  4.        case Performer performer when (performer.Age == 40):          
  5.             Console.WriteLine($"The performer {performer.Name}");          
  6.             break;          
  7.        default:          
  8.             Console.WriteLine("Not found");          
  9.             break;          
  10.        case null:          
  11.             throw new ArgumentNullException(nameof(a));          
  12. }          

Conclusion

In C# 7.0 enhancement is done in a switch statement and is an expression. Now, you can pass any object in the switch statement and do pattern matching using when clause.

Please visit my previous article (Click Here) to read about more features like Binary Literal, Digit Separator, and Local Function.

Enjoy coding .


Similar Articles