CSharp - Enum Enum Definition

Introduction

An enum is a value type with a group of named numeric constants.

For example:

public enum Direction {
   Left, Right, Top, Bottom
}

We can use this enum type as follows:

Direction topSide = Direction.Top;
bool isTop = (topSide == Direction.Top);   // true

Each enum member has an underlying integral value.

By default, the underlying values are of type int.

The constants 0, 1, 2... are automatically assigned, in the declaration order of the enum members.

You may specify an alternative integral type, as follows:

public enum Direction : byte {
   Left, Right, Top, Bottom
}
You can specify an explicit underlying value for each enum member:
public enum Direction : byte {
   Left=1, Right=2, Top=10, Bottom=11
}

You can also explicitly assign some of the enum members.

The unassigned enum members keep incrementing from the last explicit value.

The preceding example is equivalent to the following:

public enum Direction : byte{
   Left=1, Right, Top=10, Bottom
}

Related Topics

Quiz

Example