Thuta Learning
BasicProgrammingbeginner

Switch

Relax. We'll talk through this in plain words — no textbook voice.

switch statement picks one case to run out of several, based on a single value. When you'd otherwise end up chaining a long string of if...else if statements, switch keeps the code much more readable.

csharp
string role = "editor";

switch (role)
{
    case "admin":
        Console.WriteLine("Full access");
        break;
    case "editor":
        Console.WriteLine("Can create and edit content");
        break;
    case "viewer":
        Console.WriteLine("Read only access");
        break;
    default:
        Console.WriteLine("Unknown role");
        break;
}

Things to watch for

  • case runs its block when it matches the value.
  • break is used to exit the switch.
  • default runs when none of the cases match.
You should see
Can create and edit content
Switch | Thuta Learning