C# Language
* 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:
switch (expression) { case value1: // Code to be executed if expression matches value1 break; case value2: // Code to be executed if expression matches value2 break; // Additional cases as needed default: // Code to be executed if none of the cases match break; }
• Here's a simple example:
using System; class Program { static void Main() { Console.Write("Enter a number (1-3): "); int number = int.Parse(Console.ReadLine()!); switch (number) { case 1: Console.WriteLine("You entered one."); break; case 2: Console.WriteLine("You entered two."); break; case 3: Console.WriteLine("You entered three."); break; default: Console.WriteLine("Invalid input."); break; } } }
Remember: use the 'break' statement after each 'case' block to exit the 'switch' statement.
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.