Stats

1393 Contributors: 41 Sunday, July 23, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap
Download eBook

Enum

Download c# eBook

Introduction

An enum can derive from any of the following types: byte, sbyte, short, ushort, int, uint, long, ulong. The default is int, and can be changed by specifying the type in the enum definition:

public enum Weekday : byte { Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5 }

This is useful when P/Invoking to native code, mapping to data sources, and similar circumstances. In general, the default int should be used, because most developers expect an enum to be an int.

Syntax

  • enum Colors { Red, Green, Blue } // Enum declaration
  • enum Colors : byte { Red, Green, Blue } // Declaration with specific type
  • enum Colors { Red = 23, Green = 45, Blue = 12 } // Declaration with defined values
  • Colors.Red // Access an element of an Enum
  • int value = (int)Colors.Red // Get the int value of an enum element
  • Colors color = (Colors)intValue // Get an enum element from int

Remarks

An Enum (short for "enumerated type") is a type consisting of a set of named constants, represented by a type-specific identifier.

Enums are most useful for representing concepts that have a (usually small) number of possible discrete values. For example, they can be used to represent a day of the week or a month of the year. They can be also be used as flags which can be combined or checked for, using bitwise operations.

Related Examples