how does a switch case statment work C# code example

Example 1: c# switch statement

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;
}

Example 2: c# switch case with or condition

int i = 5;
switch (i)
{
    case(1):
    case(2):
        Console.WriteLine(i);
        break;
    default:
        break;
}

Tags:

Cpp Example