switch csharp code example

Example 1: c# switct case

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

Example 2: 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 3: switch c#

switch(expression) 
{
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
    break;
}

Example 4: csharp switch case

using System;
					
public class Program
{
	public static void Main()
	{
		Console.WriteLine("Enter a number");
		
		int number = Convert.ToInt32(Console.ReadLine());
		
		switch (number)
      	{
          case 1:
			  Console.Clear();
              Console.WriteLine("one");
              break;
          case 2:
			  Console.Clear();
              Console.WriteLine("two");
              break;
          default:
			  Console.Clear();
              Console.WriteLine("Default case");
              break;
      	}							
	}
}