C# switch

Switch Case in C#

In C#, the switch is a control statement that allows you to select one of many code blocks to be executed. It’s often used when you have a single expression (variable or value) that you want to compare against multiple possible values and execute different blocks of code based on which value matches the expression.

For Example :

Basic Structure :

switch (expression)
       {
          case value1:
                //code to be executed;   
               break;
            case value2:
                //code to be executed;   
                break;
                ……
            default:    
                //code to be executed if all cases are not matched;   
                break;
        }

Scenario: Write a C# program to simulate the pricing system using a switch statement. The program should take the name of the car as Mustang, Ford, or any other car and output the corresponding price. If the value doesn’t match any of the available car names, it should output “Invalid car name”.

In the below example let us see how switch code works in 3 different scenarios

Scenario1 : When car = Ford

using System;
public class Program
{
    public static void Main(string[] args)
    {
        string car = “Ford”;
        switch (car)
        {
            case “Mustang”:
                Console.WriteLine(“Price is 1cr”);
                break;
            case “Ford”:
                Console.WriteLine(“Price is 50Lakhs”);
                break;
           default:
                Console.WriteLine(“Invalid car”);
                break;
        }
   }
}

Output: Price is 50Lakhs

Code Explanation

using System;

This line is an import statement that allows you to use classes and methods from the System namespace. The System namespace contains fundamental types and base classes that are essential for all C# programs.

public class Program

This defines a public class named Program. A class is a blueprint for creating objects, and public means that this class can be accessed from outside its containing assembly.

public static void Main(string[] args)

This is the entry point of your C# program. The Main method is where execution begins. It takes an array of strings (args) as its parameter, which allows you to pass command-line arguments to your program.

string car = “Ford”;

This line declares a string variable named car and initializes it with the value “Ford”.

switch (car)

This is a switch statement that performs different actions based on the value of the car variable. Each case represents a possible value for the car, and the code within that case is executed if the car matches the case.

case “Mustang”:
                Console.WriteLine(“Price is 1cr”);
                break;

The case value is “Mustang”, and the car variable value is ”Ford” i.e. the car is not equal to Mustang, so it skips this case block of code and checks the next case

case “Ford”:
                Console.WriteLine(“Price is 50Lakhs”);
                break;

The case value is “Ford”, and the car variable value is “Ford,” i.e., the car is equal to Ford, so it executes the block of a case of value Ford and prints in the console “Price is 50 lakhs” and then exits the switch statement because of the break keyword.  

case “Mustang”:
                Console.WriteLine(“Price is 1cr”);
                break;

The case value is “Mustang”, and the car value is ”Mustang” i.e. the car is equal to Mustang, so it executes the block of case and prints in the console “Price is 1cr” and then exits the switch statement because of the break keyword. i.e the below case will not be executed.

case “Ford”:
                Console.WriteLine(“Price is 50Lakhs”);
                break;
            default:
                Console.WriteLine(“Invalid car”);
                break;
        }
    }
}

Output: Price is 1cr

You will see the above output in your console.

Scenario2 : When car = Mustang

using System;
public class Program
{
    public static void Main(string[] args)
    {
        string car = “Mustang”;
        switch (car)
        {
           case “Mustang”:
                Console.WriteLine(“Price is 1cr”);
                break;
            case “Ford”:
                Console.WriteLine(“Price is 50Lakhs”);
                break;         
            default:
                Console.WriteLine(“Invalid car”);
                break;
        }
    }
}

Output: Invalid car

Code Explanation

using System;

This line is an import statement that allows you to use classes and methods from the System namespace. The System namespace contains fundamental types and base classes that are essential for all C# programs.

public class Program

This defines a public class named Program. A class is a blueprint for creating objects, and public means that this class can be accessed from outside its containing assembly.

public static void Main(string[] args)

This is the entry point of your C# program. The Main method is where execution begins. It takes an array of strings (args) as its parameter, which allows you to pass command-line arguments to your program

string car = “Mustang”;

This line declares a string variable named car and initializes it with the value “Mustang”.

switch (car)

This is a switch statement that performs different actions based on the value of the car variable. Each case represents a possible value for the car, and the code within that case is executed if the car matches the case.

case “Mustang”:
                Console.WriteLine(“Price is 1cr”);
                break;

The case value is “Mustang”, and the car value is ”Ferrari” i.e. the car is not equal to Mustang, so it skips this case block of code and checks the next case.

case “Ford”:
                Console.WriteLine(“Price is 50Lakhs”);
                break;
           default:
                Console.WriteLine(“Invalid car”);
                break;
        }
    }
}
Output: Price is 1cr
case “Ford”:
                Console.WriteLine(“Price is 50Lakhs”);
                break;
            default:
                Console.WriteLine(“Invalid car”);
                break;
        }
    }
}
Output: Price is 1cr

You will see the above output in your console

Scenario3 : When car = Ferrari

using System;
public class Program
{
    public static void Main(string[] args)
    {
        string car = “Ferrari”;
        switch (car)
        {
            case “Mustang”:
                Console.WriteLine(“Price is 1cr”);
                break;
            case “Ford”:
                Console.WriteLine(“Price is 50Lakhs”);
                break;  
            default:
                Console.WriteLine(“Invalid car”);
                break;
        }
    }
}
Output: Invalid car

Code Explanation

using System;

This line is an import statement that allows you to use classes and methods from the System namespace. The System namespace contains fundamental types and base classes that are essential for all C# programs.

public class Program

This defines a public class named Program. A class is a blueprint for creating objects, and public means that this class can be accessed from outside its containing assembly.

public static void Main(string[] args)

This is the entry point of your C# program. The Main method is where execution begins. It takes an array of strings (args) as its parameter, which allows you to pass command-line arguments to your program

string car = “Ferrari”;

This line declares a string variable named car and initializes it with the value “Ferrari”.

switch (car)

This is a switch statement that performs different actions based on the value of the car variable. Each case represents a possible value for the car, and the code within that case is executed if the car matches the case.

case “Mustang”:
                Console.WriteLine(“Price is 1cr”);
                break;

The case value is “Mustang”, and the car value is ”Ferrari” i.e. the car is not equal to Mustang, so it skips this case block of code and checks the next case

case “Ford”:
                Console.WriteLine(“Price is 50Lakhs”);
                break;

The case value is “Ford”, and the car value is ”Ferrari” i.e. the car is not equal to Ford, so it skips this case block of code and checks the next case

default:
                Console.WriteLine(“Invalid car”);
                break;

If the car variable value doesn’t match any of the above  cases, the default case will be executed, printing “Invalid car” to the console

Output: Invalid car

You will see the above output in your console

Course Video

Task:

1.Write a C# program to simulate a simple calculator.

The program should prompt the user to enter two numbers and an arithmetic operation choice.

Prompt for first number after giving input click enter

Output

2. Prompt for second number after giving input click enter

Output

3. Display operation choice after giving input click enter

Output

4. Performed selected operation if 1 do addition

Output

5. if 2 do subtraction

Output

6. if 3 do multiplication

Output

7. if 4 do division

Output

8. If 2 input contain value  0  when we doing division then it should show a below error

Output

9. If we select operation out of 1to 4 then also it should give a below error

Output

10. Day of the Week:
Create a method that takes an integer (1 to 7) representing the day of the week.
Use a switch statement to print the name of the day (e.g., 1 = Sunday).
Inside each case, use an if-else statement to print if the day is a weekday or weekend.

11. Grade Classification:
Create a method that takes a char (A, B, C, D, F) representing a grade.
Use a switch statement to print the full form of the grade (e.g., A = “Excellent”).
Inside the switch cases for A, B, and C, use an if-else statement to print a motivational message if the grade is A or B.

12. Season Checker:
Create a method that takes a string representing a season (Winter, Spring, Summer, Fall).
Use a switch statement to print an activity associated with that season.
Inside the switch cases, use an if-else statement to check if the season is “Summer” and print an additional message about staying hydrated.

13. Employee Role:
Create a class Employee with properties Name and Role.
In the main method, create an Employee object and use a switch statement on the Role property to print different messages for different roles (e.g., Manager, Developer, Intern).
Inside each switch case, use an if-else statement to print a different message if the Name is “John”.

14. Traffic Light:
Create a method that takes a string representing a traffic light color (Red, Yellow, Green).
Use a switch statement to print actions for each color (e.g., Red = “Stop”).
Inside the switch case for Yellow, use an if-else statement to print a different message if a boolean variable isPedestrian is true.

15. Shopping Discount:
Create a method that takes a string representing the type of customer (Regular, Member, VIP).
Use a switch statement to apply different discount percentages.
Inside each switch case, use an if-else statement to apply an additional discount if the purchase amount is over $100.

16. Browser Type:
Create a method that takes a string representing a browser name (Chrome, Firefox, Safari, Edge).
Use a switch statement to print the developer of the browser.
Inside the switch case for Chrome, use an if-else statement to check the version number and print if it is up-to-date.

17. Month Days:
Create a method that takes an integer (1 to 12) representing a month.
Use a switch statement to print the number of days in the month.
Inside the switch case for February, use an if-else statement to print if it is a leap year.

18. Vehicle Type:
Create a class Vehicle with properties Type and Speed.
In the main method, create a Vehicle object and use a switch statement on the Type property (Car, Bike, Truck).
Inside each switch case, use an if-else statement to print a warning if the Speed is over a certain limit.

19. Menu Options:
Create a method that takes an integer (1 to 5) representing a menu option.
Use a switch statement to print different messages for each menu option.
Inside each switch case, use an if-else statement to print an additional message if a boolean variable isAdmin is true.