C# Switch

Concept of switch statement in C#.

* Switch case is often more efficient than 'if-else' chains when handling multiple conditions, as it directly jumps to the matching case instead of evaluating each condition sequentially.

Switch Case

The 'switch' statement is a control flow statement that allows you to select one of many code blocks to be executed based on the value of an expression. Here's the basic syntax of a 'switch' statement:

1switch (expression)
2{
3case value1:
4// Code to be executed if expression matches value1
5break;
6
7case value2:
8// Code to be executed if expression matches value2
9break;
10
11// Additional cases as needed
12
13default:
14// Code to be executed if none of the cases match
15break;
16}

Here's a simple example:

cs Copy Code
1using System;
2
3class Program
4{
5static void Main()
6{
7Console.Write("Enter a number (1-3): ");
8int number = int.Parse(Console.ReadLine()!);
9
10switch (number)
11{
12case 1:
13Console.WriteLine("You entered one.");
14break;
15
16case 2:
17Console.WriteLine("You entered two.");
18break;
19
20case 3:
21Console.WriteLine("You entered three.");
22break;
23
24default:
25Console.WriteLine("Invalid input.");
26break;
27}
28}
29}

Remember: use the 'break' statement after each 'case' block to exit the 'switch' statement.

Output:
Enter a number (1-3): 2
You entered two.

In this example, the user is prompted to enter a number, and the program uses a 'switch' statement to determine which message to display based on the entered number. The 'default' case is executed if none of the specified cases match the value of the expression ('number' in this case).

What's Next?

We've now entered the finance section on this platform, where you can enhance your financial literacy.