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
3 odpowiedzi
+ 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
+ 3
switch is just like if/else statement, it have a case,Break and default:- Case: is a condition it can be only integers and giving a flaot condition cause error. Break: It is just like a bracket of a if case which separates the if case from other code just like that, if the condition cass met than it starts calling and if Their in no break statement it will go till the last case that's why it important to put a break in every case. Default: it just like the else statement, it mean when no condition met than default statement get called.
11th Sep 2024, 1:51 PM
Alhaaz
Alhaaz - 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