C# Switch | C# Switch case | C# Switch Statement - c# - c# tutorial - c# net



C# Switch

C# Switch

What is C# Switch case ?

  • Switch case is also another condition constructs in C# programming.
  • The switch statement is a controlstatement that selects a switch section to execute from a list of values.
  • Each value is called a case, and the variable being switched on is checked for each switch case.
  • learn c# - c# tutorial - c# csharp switch case statement- c# examples -  c# programs
  • It also includes a default value in Default statements. If no any case matches, then Default statements executes and run the code.
 structure of switch statement

Syntax:

switch (n) {
    case label1:
        code to be executed if n=label1;
        break;
    case label2:
        code to be executed if n=label2;
        break;
    ...
    default:
        code to be executed if n is different from all labels;
}

C# Sample Code - C# Examples:

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
namespace wikitechy_switch_statement
{
classProgram
    {
staticvoid Main(string[] args)
        {
charwikitechy = '1';

switch (wikitechy)
            {
case'0':
Console.WriteLine("wikitechy says this is DotNet");
break;
case'1':
Console.WriteLine("wikitechy says this is C#");
break;
case'2':
Console.WriteLine("wikitechy says this is Java");
break;
case'3':
Console.WriteLine("wikitechy says this is C");
break;
default:
Console.WriteLine("wikitechy says this is failure");
break;
            }

Console.ReadLine();
        }
    }
}

Code Explanation:

 code of switch statement
  1. charwikitechy = '1'; specifies the character wikitechy = 1 these holding the values of 1.
  2. Here,switch (wikitechy) will call the "wikitechy" in the code, which we have specified as "1".
  3. We have theswitch-cases as case "1", case "2" and case "3" which executes based on the function call for that wikitechy. If these cases fail it will execute the default case statement. Here break; is a statement that executes a line break in the code execution. And Console.WriteLine, the Main method specifies its behavior with the statement "WikiTechy says this is C#" to be displayed on the screen.
  4. If no case label contains a matching value, control is transferred to the default section.
  5. Here Console.ReadLine(); specifies to reads input from the console. When the user presses enter, it returns a string.

Sample C# examples - Output :

 output of switch statement
  1. Here in this output we display the "Wikitechy says this is C#" which specifies to console statement.

Related Searches to C# Switch | C# Switch Statement