Monday, October 22, 2018

C# : Switch Case With When

In C#, Switch - Case statement is just alternative of IF-ELSE statement and it allows a variable to be equality compared against list of case values.



Example :
     string colorCode = "R";

            string Color = string.Empty;
            switch (colorCode)
            {
                case "R":
                    Color = "RED";
                    break;

                case "B":
                    Color = "BLUE";
                    break;

                case "Y":
                    Color = "YELLOW";
                    break;
                default:
                    Color = "UNKNOWN";
                    break;

            }
           
            Console.WriteLine(Color);
          
Output :
                RED  

but It is a very simple equality check , if you want to perform greater, less than or range pattern matching. It will not help you let’s see a real problem.

Problem:  Show student examination result based on student mark:

Mark < 32: Failed
Mark >=32 AND Mark <= 45: 3rd Grade
Mark > 45 AND Mark <= 60: 2nd Grade
Mark > 60: 1st Grade



In C# 7.0, C# introduce new Case-When Clause, where you can apply additional condition on that.

            int mark = 34;
            string ExamResult = string.Empty;
            switch (mark)
            {
                case int m when (m < 32):
                    ExamResult = "FAILED";
                    break;

               case int m when (m >= 32 && m <= 45):
                    ExamResult = "3rd Grade";
                    break;

                case int m when (m > 45 && m <= 60):
                    ExamResult = "2nd Grade";
                    break;

               case int m when (m > 60):
                    ExamResult = "1st Grade";
                    break;

                default:
                    ExamResult = "InValid";
                    break;

            }

                      Console.WriteLine(ExamResult);

Output :
                3rd Grade

Thanks for Visiting!!

1 comment:

Biswajit Das said...

Nice article. It's very helpful to me. Thank you for share with us. Can you please check my Top logo color hex code collection.

Azure Load Balancing Services: Choosing the Right Solution

As organizations move applications to Azure, selecting the right load balancing service becomes critical for performance, availability, and ...