Tag Archive for enum

[C#] Enumeration Types Summary

An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable.

Usually it is best to define an enum directly within a namespace so that all classes in the namespace can access it with equal convenience. However, an enum can also be nested within a class or struct.

Every enumeration type has an underlying type (byte, sbyte, short, ushort, int, uint, long, or ulong), which can be any integral type except char. The default underlying type of enumeration elements is int. To declare an enum of another integral type, such as byte, use a colon after the identifier followed by the type.

The default value of an enum E is the value produced by the expression (E)0, and the value of each successive enumerator is increased by 1 if it’s not explicitly assigned. When you create an enum, select the most logical default value and give it a value of zero, or you can consider creating a None enumerated constant. That will cause all enums to have that default value if they are not explicitly assigned a value when they are created.

When assigning values to the elements in the enumerator list, you can also use coputed values, for example:

enum MachineState
{
PowerOff = 0,
Running = 5,
Sleeping = 10,
Hibernating = Sleeping + 5
}

Read more