• Startseite
  • Tutorials
  • Kontakt
  • Mein Account
Panjutorials
  • Startseite
  • Tutorials
  • Kontakt
  • Mein Account

Switch statement in CSharp

In this lecture we are going to cover the switch statement in CSharp. It is an alternative to the if statement and is very similar. It is mainly the preference of the developer which of the two is used, but in some cases a switch statement can be easier to read.

Example for a Switch Case in CSharp

int age= 25;

switch (age)
{
    case 15:
        {
            Console.WriteLine("Underage, huh?");
            break;
        }
    case 25:
        {
            Console.WriteLine("Grow up dude!");
            break;
        }
    default:
        {
            Console.WriteLine("Can't even imagine your age");
            break;
        }

}            
Console.Read();

In the round brackets after the switch you enter the variable you want to examine. This must be a variable that can be converted into an integer. Then follow braces {} and the different “cases”.

case: then the number you want to check followed by a colon. Following, in braces, the code you want to execute. You shouldnt forget break; Otherwise, an error is displayed. Unlike in e.g. Java where it would execute the code of the first case that was met and then just go to the next case until a “break” comes. This is not possible in CSharp though! Default can be compared to the else in the if else if statment. So if none of the foregoing cases is met, the code within the braces {} after default: will be executed.