The switch Statement

It’s a tradition to introduce the switch statement using the if statement first. Consider the following fragment:

Image GetBackgroundForColorScheme(Color color){    if (color == Color.Red)        return Image.FromFile("Roses.png");    else if (color == Color.Green)        return Image.FromFile("Grass.png");    else if (color == Color.Blue)        return Image.FromFile("Sky.png");    else        throw new InvalidOperationException("Expected primary color.");}

I’m using some System.Drawing types such as Color and Image in the preceding fragment, but ignore this detail for just a second and focus on what makes this fragment tick.

Programmers often refer to this if statement pattern as a multiway ...

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.