CSharp/C# Tutorial - C# if switch






The if Statement syntax should be fairly intuitive for anyone who has done any programming with a procedural language:


if (condition) 
   statement(s) 
else 
   statement(s) 

If more than one statement is to be executed as part of either condition, these statements need to be grouped together into a block using curly braces ({.}).


bool isZero; 
if (i == 0) { 
  isZero = true; 
  Console.WriteLine("i is Zero"); 
} else { 
  isZero = false; 
  Console.WriteLine("i is Non-zero"); 
} 

An if statement executes a statement if a bool expression is true.

For example:


if (5 < 2 * 3) {
    Console.WriteLine ("true"); // true 
}

The statement can be a code block:


if (5 < 6) {
 Console.WriteLine ("true");
 Console.WriteLine ("Let's move on!"); 
} 




The else clause

An if statement can optionally have an else clause:


if (1 == 2){
   Console.WriteLine ("equal"); 
}else{
   Console.WriteLine ("False"); // False 
}

Within an else clause, you can nest another if statement:


if (4 == 5){
   Console.WriteLine ("4 is 5"); 
}else if (2 + 2 == 4) {
   Console.WriteLine ("4 is 4"); // Computes 
}




The switch statement

switch statements can branch program execution based on a selection of possible values.

For instance:


void ShowCard(int cardNumber) { 
    switch (cardNumber) {
        case 13: 
            Console.WriteLine ("King"); 
            break;
        case 12: 
            Console.WriteLine ("Queen"); 
            break;
        case 11: 
            Console.WriteLine ("Jack"); 
            break;
        case -1: 
            goto case 12;
        default:/* ww  w  .ja  v  a  2  s .c o  m*/
            Console.WriteLine (cardNumber); 
            break; 
    } 
} 

We can switch on an expression of the following types that can be statically evaluated

  • integral types
  • bool
  • enum types
  • string type.

At the end of each case clause, we must set where execution is to go next, with a jump statement.

Here are the options:

  • Use break statement to jump to the end of the switch statement
  • Use goto case x statement to jump to another case clause
  • Use goto default statement to jump to the default clause
  • Use other jump statement, return, throw, continue, or goto label

When more than one value should execute the same code, you can list the common cases sequentially:


switch (cardNumber) { 
    case 13: //from   w  ww. ja v a  2  s  .c  o m
    case 12: 
    case 11:
        Console.WriteLine ("J Q K"); 
        break;
    default: 
        Console.WriteLine ("Number"); 
        break; 
}