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 ...

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.