Revisiting the switch Statement

Code often has to dispatch to certain logic based on an enum value. One of the best candidate statements to carry out this task is the switch statement. In fact, the code editor in Visual Studio has a handy feature for generating a full switch statement for all of an enum’s members. Here’s the way to do it: Given a variable of an enum type, type switch and press Tab twice. Now enter the variable name and press Enter. For our Color type, this technique is illustrated in Figure 11.10.

Image

FIGURE 11.10 Generating a switch statement for an enum.

Although it might seem tempting to get rid of the default branch, this isn’t ...

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.