The enum keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list. Every enumeration type has an underlying type, which can be any integral type except char. The declaration of an enum variable takes the form:
[attributes] [modifiers] enum identifier [:base-type] {enumerator-list};
where:
The default type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by one. For example:
enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};
In this enumeration, Sat
is 0
, Sun
is 1
, Mon
is 2
, and so forth. Enumerators can have initializers to override the default values. For example:
enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
In this enumeration the sequence of elements is forced to start from 1
instead of 0
.
The default value of a enum E is the value produced by the expression (E)0
.
For more information on enumeration types, see §14 in the language reference.
// enum initialization: using System; public class EnumTest { enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri}; public static void Main() { int x = (int) Days.Sun; int y = (int) Days.Fri; Console.WriteLine("Sun = {0}", x); Console.WriteLine("Fri = {0}", y); } }
Sun = 2
Fri = 7
However, if you remove the initializer from Sat=1
, the result will be:
Sun = 1
Fri = 6
In this example, the base-type option is used to declare an enum whose members are of the type long.
// Using long enumerators
using System;
public class EnumTest {
enum Range :long {Max = 2147483648L, Min = 255L};
public static void Main() {
long x = (long) Range.Max;
long y = (long) Range.Min;
Console.WriteLine("Max = {0}", x);
Console.WriteLine("Min = {0}", y);
}
}
Max = 2147483648
Min = 255
C# Keywords | Default Values Table | Built-in Types Table | Types Categories | Value Types