| only for RuBoard - do not distribute or recompile |
|
Syntax: |
|---|
attributes? access-modifier?
new?
enum enum-name [ : integer type ]?
{ [attributes? enum-member-name [ = value ]? ]* }
|
Enums specify a group of named numeric constants:
public enum Direction {North, East, West, South}
Unlike in C, enum members must be used with the enum type name. This resolves naming conflicts and makes code clearer:
Direction walls = Direction.East;
By default, enums are assigned integer constants: 0, 1, 2, etc. You can optionally specify an alternative numeric type to base your enum on and explicitly specify values for each enum member:
[Flags]
public enum Direction : byte {
North=1, East=2, West=4, South=8
}
Direction walls = Direction.North | Direction.West;
if((walls & Direction.North) != 0)
System.Console.WriteLine("Can't go north!");
The [Flags] attribute is optional. It informs the runtime that the values in the enum can be bit-combined and should be decoded accordingly in the debugger or when outputting text to the console. For example:
Console.WriteLine(walls); // Displays "North, West"
Console.WriteLine(walls.ToString("d")); // displays "5"
The System.Enum type also provides many useful static methods for enums that allow you to determine the underlying type of an enum, check if a specific value is supported, initialize an enum from a string constant, retrieve a list of the valid values, and perform other common operations such as conversions. Here is an example:
using System;
public enum Toggle : byte { Off=0, On=1 }
class TestEnum {
static void Main( ) {
Type t = Enum.GetUnderlyingType(typeof(Toggle));
Console.WriteLine(t); // Prints "System.Byte"
bool bDimmed = Enum.IsDefined(typeof(Toggle), "Dimmed");
Console.WriteLine(bDimmed); // Prints "False"
Toggle tog =(Toggle)Enum.Parse(typeof(Toggle), "On");
Console.WriteLine(tog.ToString("d")); // Prints "1"
Console.WriteLine(tog); // Prints "On"
Array oa = Enum.GetValues(typeof(Toggle));
foreach(Toggle atog in oa) // Prints "Off=0, On=1"
Console.WriteLine("{0}={1}", atog, atog.ToString("d"));
}
}
The operators relevant to enums are:
|
== |
<= |
|||
|
+ |
||||
|
|
Enums can be explicitly converted to other enums. Enums and numeric types can be explicitly converted to one another. A special case is the numeric literal 0, which can be implicitly converted to an enum.
| only for RuBoard - do not distribute or recompile |