Why Enums Matter

One key difference with constants defined on (and exposed by) some type is the fact an enum puts all related constant values under a common umbrella. Because of this, stronger typing ensues, (partly) avoiding invalid assignments. The use of our Color enum is shown here on the first line; the second line is invalid:

Color red = Color.Red;Color blue = 17;  // Invalid assignment.

Notice that we’ve stated that invalid assignment to an enum-typed variable is only partly mitigated because an explicit conversion from the underlying type to an enum exists. This allows for easy serialization scenarios where an enum’s value is stored away and put back in after deserialization. As you will see later, enums can also be used for “flag masks,” ...

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.