C# Switch statement

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.

C# Switch statement

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.


Share Tweet Send
Loading...
You've successfully subscribed to Geekinsta
Great! Next, complete checkout for full access to Geekinsta
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.