switch statement in C# is a way to run different pieces of code based on the value of a variable. It’s like a more organized version of multiple
if statements.
Here’s a simple example to illustrate how it works:
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
default:
Console.WriteLine("Weekend");
break;
}
Explanation:
- Variable to Check: The
switch statement checks the value of day. - Cases: Each
case is a possible value for day. For example, if day is 1, it will print "Monday". - Break: Each
case ends with a break statement, which stops the code from running any further cases once a match is found. - Default: The
default block runs if none of the cases match. In this example, it prints "Weekend" if day is not 1 to 5.
The switch statement is useful when you have a variable that can take several different values and you want to do something specific for each value.
اديلو
ReplyDelete🔥👾🤡🤯
ReplyDelete