Intermezzo: The Mythical Type Switch

The switch statement is a convenient way to express multiway branches that would normally get written using tons of if statements. Switches typically operate based on compile-time constant values, and that’s no different in C#:

switch (card.Type){    case CardType.Credit:        // Do something.        break;    case CardType.Debit:        // Do something else.        break;    default:        // Other type of card. Do yet something else.        break;}

We talk extensively about the switch statement in Chapter 7, “Simple Control Flow,” but I want to point out one thing here: C#’s switch statement does not support “switch on type.”

There are various reasons for this. First, the ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.