Conditional Blocks

by CameronM 3. February 2009 18:27

Conditional blocks or selection statements provide a mechanism for choosing between alternate blocks of code.

if-then

The most common of the selection statements is the if-then statement that runs different blocks of code depending on the results of a condition. Conditions can be any expression that returns a Boolean, such as comparing two numbers.

// using a single comparison condition
if(myVariable1 > 0)
{
    Console.WriteLine("Bigger than zero");
}
else
{
    Con

When the condition evaluates to true, the ‘then’ portion of the statement runs. Unlike VB, in C# you don’t need to explicitly use the Then keyword, anything directly after the condition (usually in the curly braces) is the then statement. I said usually in the curly braces, because if your then block consists of only one line of code, you can omit the braces.

// omit the curly braces {} for single lines of code
if(myVariable1 > 0)
    Console.WriteLine("Bigger than zero");

The condition can include more than one comparison using logical operators, such as && (and) or || (or)

// using the && (and) logical operator - both expressions must be true
if(myVariable1 == 0 && myVariable2 == 10)
{
    Console.WriteLine("Both are true");
}
 
// using the || (or) logical operator - either expression may be true
if (myVariable1 == 0 || myVariable2 != 10)
{
    Console.WriteLine("One value is true");
}

switch

The switch statement runs one of the number of code blocks based on the value of the switch expression. Each code block begins with a case keyword and a value to compare against the switch expression. If the case and switch expression match, the code in that section runs. Instead of each block of code being delineated by curly braces, a jump statement (usually break) is used to exit the switch. 

// compare the value of myVariable1 against 3 different case 
// the last is the catch-all or default that runs if neither
// of the previous sections offer a match
switch (myVariable1)
{
    case 0:
        Console.WriteLine("Equal to zero");
        break;
    case 1:
        Console.WriteLine("Equal to one");
        break;
    default:
        Console.WriteLine("Some other number");
        break;
}

Tags:

C#