0

Need Help c# ,Again!!

What Is "Switch" in C#?How Does It Work? And How To Use It?

11th Sep 2024, 1:46 PM
HASAN IMTIAZ
HASAN IMTIAZ - avatar
2 ответов
+ 2
The switch statement in C# is a way to check a variable's value and run different blocks of code depending on what that value is. It's like a more organized version of multiple if-else statements. Here’s a simple example: 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; } In this example: The switch checks the value of day. If day is 1, it prints "Monday". If day is 2, it prints "Tuesday", and so on. The default case runs when none of the other cases match (like an "else" in an if-else). The break tells the program to stop checking other cases once it finds a match. So, for day = 3, it will print "Wednesday."
12th Sep 2024, 5:19 AM
Monica Martinez
Monica Martinez - avatar
+ 1
Switch is a fancy if / else if / else statement, good when there are several possible values in the variable you are testing. Here is an example of a C# program using a switch statement: using System; class Program { static void Main() { 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; case 6: Console.WriteLine("Saturday"); break; case 7: Console.WriteLine("Sunday"); break; default: Console.WriteLine("Invalid day"); break; } } }
11th Sep 2024, 2:02 PM
Jerry Hobby
Jerry Hobby - avatar