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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.