Why do a lot of people do enums this way:
public enum EmployeeRole
{
None = 0,
Manager = 1,
Admin = 2,
Operator = 3
}
instead of just doing:
public enum EmployeeRole
{
None,
Manager,
Admin,
Operator
}
Are there advantages?
If you use enums instead of integers (or String codes), you increase compile-time checking and avoid errors from passing in invalid constants, and you document which values are legal to use.
Enums are used when we know all possible values at compile-time, such as choices on a menu, rounding modes, command-line flags, etc. It is not necessary that the set of constants in an enum type stay fixed for all time. In Java (from 1.5), enums are represented using enum data type.
Since Enums can be any integral type ( byte , int , short , etc.), a more robust way to get the underlying integral value of the enum would be to make use of the GetTypeCode method in conjunction with the Convert class: enum Sides { Left, Right, Top, Bottom } Sides side = Sides.
Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.
Are there advantages?
Maintainability. Let's say these integer values end up persisted in a database. You don't want to add a new value to the enum in the future and have the values change because you insert a value in a way that shifts the unspecified values.
Clarity. Explicitness is a good thing. Let's say again we're reading integers out of a database from some legacy application. So the codes already have a specific meaning, and we want to explicitly line up with them. We could say
public enum EmployeeRole {
None,
Manager,
Admin,
Operator
}
and maybe that lines up exactly with the legacy specification or we could say
public enum EmployeeRole {
None = 0,
Manager = 1,
Admin = 2,
Operator = 3
}
and now it is easier to read whether or not we line up with the legacy specification.
It is useful when you have a contract elsewhere. If you store the enum in a database you want to type the numbers explicitly to be sure you don't accidentally renumber the enum by inserting a new item in the middle.
It explicits defines a value rather than letting the compiler handle it at compile time. In the case you provided, it really serves no point other than being readable and and well-defined. It doesn't hurt anything and results in the same MISL as not explicitly setting them. However, in cases where your enums relate to specific values that are not auto-incremented as the above case is, this kind of explicit definition comes in very handy.
public enum MyEnum
{
First = 1,
Second = 2,
Eleventh = 11
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With