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 branch. In fact, here we’re using ...

Get C# 4.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.