What is the Enumeration in C# ???
An Enumeration in C#, or enum, is a distinct value type that consists of a set of named constants called the enumerator list. Enums are used to declare a collection of constants that represent related values.
Syntax – Enumeration in C#
enum EnumName
{
Value1,
Value2,
Value3
}
Example –
using System; namespace EnumExample { class Program { enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } static void Main(string[] args) { Days today = Days.Wednesday; Console.WriteLine("Today is: " + today); Console.WriteLine("Day number: " + (int)today); } } }
Line-by-Line Notes
namespace EnumExample
- Defines a namespace called “
EnumExample
” to organize the code and prevent naming conflicts.
enum Days
- Declares an enumeration named
Days
. enum
: Keyword to declare an enumeration.Days
: Name of the enumeration.
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
- Lists the named constants of the “
Days
” enumeration. By default, the first enumerator has the value0
, and each subsequent enumerator has a value that is incremented by1
.
Days today = Days.Wednesday;
- Declares a variable named
today
of typeDays
and assigns it the valueDays.Wednesday
. Days
: Data type of thetoday
variable, which is theDays
enumeration.today
: Name of the variable.Days.Wednesday
: Value assigned to thetoday
variable, representing Wednesday.
Console.WriteLine("Day number: " + (int)today);
- Outputs the underlying integer value of the
today
variable to the console. (int)today
: Casts thetoday
variable to its underlying integer value."Day number: " + (int)today
: Concatenates the string"Day number: "
with the integer value oftoday
.