C# Switch statement
C Sharp

C# Switch statement

Editorial Team
Editorial Team

Follow us on Discord or Telegram to get access to free tutorials and updates.

A switch statement acts as an if-else-if ladder. It can have an optional default case which is specified at the end of the switch statement. The default case will be executed if none of the cases provided is true.

Syntax

switch (expression) 
{
  case case1:
    statements;
    break;
  case case2:
    statements;
    break;
  default:
    statements;
    break;
}

Example

using System;
namespace LearnCSharp
{
  class Program
  {
	static void Main(string[] args)
	{
		string name = "John";
		switch (name) 
                {
		  case "Joe":
			Console.WriteLine("I am Joe");
			break;
		  case "Sam":
			Console.WriteLine("I am Sam");
			break;
		  case "John":
			Console.WriteLine("I am John");
			break;
		  case "Steev":
			Console.WriteLine("I am Steev");
			break;
		  default:
			Console.WriteLine("I will be executed only if no cases are true");
		}
	}
    Console.ReadLine();
  }
}

The output will be

I am John

Writing a case

DatatypeCase
Integercase 1:
    //do this;
    break;
Charcase 'a':
    //do this;
    break;
Stringcase "string"
    //do this;
    break;

Learn more about other control statements.