General C# – Enumarators

What are Enumarators and How they Work

Eumarations are a distinct value type different from structs. They are used to represent a finite set of integral types (except for char), and do not contain constructors, methods, operators, events… In this way an enumaration can be viewed as a very special case of a user-defined struct type with a set of integral type constants. The main benefits of using enums over integral constants are: (1) you clearly specify which set of values are valid for a variable, (2) In VS, IntelliSense will list the available set of values, and (3) it enforces strong typing.

For Example, if you can have the following constant set for days and months:

public const int Jan = 0;
public const int Dec = 12;
public const int Sunday = 0;

Or you can use the enum type instead:

enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
enum Months { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec };

The second solution is much tidier and shorter–2 lines of code versus 19; The second solution also gives you IntelliSense support, which clearly identifies which variables are valid. Most importantly, in the second method, you cannot cast the wrong type. I.e. enum’s are strong typed and you cannot do this:

int postingDay = Jan; // compiler will not have a problem with this and this error might go un-noticed.
Days positingDay = Months.Jan; // Compiler will throw an error

Of course, this is a silly example, but if the code gets very complex and references are greatly abstracted, this is not a hard mistake to make!

MSDN VS2010 Article

A note

Don’t confuse enumerations (what I talk about here) with enumerables, which are objects that support being enumerated over such as List.

Leave a Reply

Your email address will not be published. Required fields are marked *