xxxxxxxxxx
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}
xxxxxxxxxx
string commandName = "start";
switch (commandName)
{
case "start":
Console.WriteLine("Starting service...");
StartService();
break;
case "stop":
Console.WriteLine("Stopping service...");
StopService();
break;
default:
Console.WriteLine(String.Format("Unknown command: {0}", commandName));
break;
}
xxxxxxxxxx
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}
xxxxxxxxxx
// switch..case with string
void StringSwitchCase()
{
string name = "Mahesh";
switch (name)
{
case "Mahesh":
Console.WriteLine("First name was used!");
break;
case "Chand":
Console.WriteLine("Last name was used!");
break;
default:
Console.WriteLine("No name found!");
break;
}
}
xxxxxxxxxx
//EXAMPLE
int day = 4;
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;
default:
Console.WriteLine("Sunday");
break;
}
xxxxxxxxxx
using System;
public class Example
{
public static void Main()
{
int caseSwitch = 1;
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
default:
Console.WriteLine("Default case");
break;
}
}
}
// The example displays the following output:
// Case 1
xxxxxxxxxx
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1");
DateTime date = DateTime.Today;
Console.WriteLine("Today's date is {0}", date);
if (date.Day == 2)
{
Console.WriteLine("This is the shortest month");
}
break;
case 2:
Console.WriteLine("Case 2");
break;
case 3:
Console.WriteLine("Case 3");
break;
default:
Console.WriteLine("Default case");
break;
}
xxxxxxxxxx
// switch..case with enum
void WeekEndOrWeekDay()
{
switch (DateTime.Now.DayOfWeek)
{
case DayOfWeek.Saturday:
case DayOfWeek.Sunday:
Console.WriteLine("Today is Weekend");
break;
default:
Console.WriteLine("Today is a work day.");
break;
}
}
xxxxxxxxxx
int something = 2;
switch(something)
{
case 1:
Console.WriteLine(1);
break;
case 2:
Console.WriteLine(2);
break;
}
xxxxxxxxxx
// Generate a random value between 1 and 9
int caseSwitch = new Random().Next(1, 9);
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
case 3:
Console.WriteLine("Case 3");
break;
default:
Console.WriteLine("Value didn't match earlier.");
break;
}