Conditional Statement Facts

The following table describes three conditional blocks available with C#.

Type Example Explanation
if-else
if(x == 0)
   FunctionA();
else if(y == 0)
   {
   FunctionB();
   FunctionC();
   }
else if(z == 0)
   {
   if(zz == 0)
       FunctionD();
   }
else
   FunctionE();
if blocks have the following characteristics:

  • The condition must evaluate to a boolean expression (true or false).
  • When the condition is true, the block following the if statement (called the body) is executed. When the condition is false, the code block following the if block is executed (either an else block or the next block of code).
  • Braces within the blocks are optional when the block includes a single statement.
  • if statements can be nested (or chained). When doing so, it can be difficult to distinguish where one code block ends. Add braces to explicitly identify where each block begins and ends.
switch
switch(x)
{
   case 1:
      // code here
      break;
   case 2:
   case 3:
   case 4:
      // code here
      break;
   case 5:
      // code here
      return;
   case 6:
      // code here
      goto case 1;
   default:
      // code here
      break;
}

Be aware of the following about switch statements:

  • The parameter of the switch statement must be one of the following types:
    • Integral
    • String
    • Enum
    • User-defined type with exactly one implicit conversion to an integral type or string
  • The body of a switch statement must be surrounded by braces.
  • The body may contain zero or more case statements. Each case statement corresponds to exactly one value.
  • A case statement value must be compile-time constant (literal values or constants only).
  • Control may only fall from one case statement to another if there is no code between the two statements. In this example, cases 2, 3, and 4 execute the same code block.
  • To prevent control from reaching the end of a case statement, use one of the following constructs in each case block:
    • break (the most common) sends control to the first statement after the switch body
    • return returns from the current function
    • throw throws an exception (branches to error handling code)
    • goto branches to the specified labeled statement
  • The body may contain one default statement. The default statement must appear after all the case statements and must include a break or similar statement.
ternary
return ((x == 0) ? "Hello" : "Goodbye")
The ternary operator is used as shorthand notation for an if-else construct. It is called ternary because it takes three operands.

  • The conditional statement. Like an if-else statement, the condition must evaluate to a boolean value and must be followed by a question mark.
  • The value to return if the condition is true (in this example, the word "Hello").
  • The value to return if the condition is false (in this example, the word "Goodbye").