Tech moves fast! Stay ahead of the curve with Techopedia!
Join nearly 200,000 subscribers who receive actionable tech insights from Techopedia.
Enum, in C#, is a keyword that represents a value type for declaring a set of named constants.
An enum helps to define a series of related integral constants that represent special values within a module of code. An enum can be used in a switch statement, which is used as a decision-making statement for comparing numeric values. It helps to create, maintain and enhance the self-documenting code that needs additional constants in the later versions of the software. An enum is preferred while representing a set of mutually exclusive values. It can be used to represent bitflags and hence can be used to perform logical operations like AND, OR, XOR, etc.
An enum has a better advantage than using integral numeric type because it clearly specifies the range of values that the client code can use, and the values are displayed in the Intellisense of Visual Studio. The use of enums brings the advantage of type safety by assigning the numeric variable in a program with meaningful enum values.
Enum is also called enumeration or an enumerator list.
While declaring a value of enum type, the details can include the name, accessibility, underlying type and the names of enum members. The default underlying type, which is a 32-bit integer (int), can be overridden with any integral type (except "char"). The default type of an enum is "int".
For example, an enumeration can be declared to list the months of a year to display in both integer and string form.
The value of an enum member can be assigned explicitly or implicitly. For an enum member that is not assigned explicitly, the first value is set to zero and the members after that each have an associated value that's equal to one more than the value of its predecessor. However, the default values can be overridden by using initializers.
Two members of an enum cannot have the same name but can share the same associated value. The values specified for the members of an enum should be within the range of the underlying type of the enum. The underlying value of an enum member can be obtained by performing an explicit cast to convert it to its integral type.