Selection Statements: if and switch

The selection statements perform operations based on the value of an expression.

1. if

The if statement in C# requires that the condition inside the if statement evaluate to an expression of type bool. In other words, the following is illegal:

// error using System;

class Test {

public static void Main()

{

int value;

if (value)                        // invalid

System.Console.WriteLine(“true”);

if (value == 0)                 // must use this

System.Console.WriteLine(“true”);

}

}

2. switch

switch statements have often been error-prone; it’s just too easy to inadvertently omit a break statement at the end of a case or, more likely, to not notice that there’s fall-through when reading code.

C# gets rid of this possibility by requiring that there be either a break at the end of every case block or a goto another case label in the switch. For example:

using System; class Test {

public void Process(int i)

{

switch (i)

{

case 1:

case 2:

// code here handles both 1 and 2

Console.WriteLine(“Low Number”);

break;

case 3:

Console.WriteLine(“3”);

goto case 4;

case 4:

Console.WriteLine(“Middle Number”);

break;

default:

Console.WriteLine(“Default Number”);

break;

}

}

}

C# also allows the switch statement to be used with string variables:

using System; class Test {

public void Process(string htmlTag)

{

switch (htmlTag)

{

case “P”:

Console.WriteLine(“Paragraph start”);

break;

case “DIV”:

Console.WriteLine(“Division”);

break;

case “FORM”:

Console.WriteLine(“Form Tag”);

break;

default:

Console.WriteLine(“Unrecognized tag”);

break;

}

}

}

Not only is it easier to write a switch statement than a series of if statements but it’s also more efficient, as the compiler uses an efficient algorithm to perform the comparison.

For small numbers of entries1 in the switch, the compiler uses a feature in the .NET runtime known as string interning. The runtime maintains an internal table of all constant strings so that all occurrences of that string in a single program will have the same object. In the switch, the compiler looks up the switch string in the runtime table. If it isn’t there, the string can’t be one of the cases, so the default case is called. If it’s found, a sequential search is done of the interned case strings to find a match.

For larger numbers of entries in the case, the compiler generates a hash function and hash table and uses the hash table to efficiently look up the string.

Source: Gunnerson Eric, Wienholt Nick (2005), A Programmer’s Introduction to C# 2.0, Apress; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *