English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In C#, enum (enumeration type) is used to assign constant names to a set of integer values. It makes constant values more readable, for example, WeekDays.Monday is more readable when referring to a day of the week than the number 0.
Enumerations are defined directly using the enum keyword within a namespace, class, or structure. All constant names can be declared within the braces and separated by commas. Below is defined the enumeration for weekdays.
enum WeekDays { Monday Tuesday Wednesday Thursday, Friday, Saturday, Sunday }
Above, the WeekDays enumeration declares members on each line, separated by commas.
If no value is assigned to an enumeration member, the compiler will assign integer values (starting from zero) by default to each member. The first member of the enumeration will be 0, and the value of each subsequent enumeration member will increase1.
enum WeekDays { Monday // 0 Tuesday // 1 Wednesday // 2 Thursday, // 3 Friday, // 4 Saturday, // 5 Sunday // 6 }
You can assign different values to enumeration members. Changing the default value of enumeration members will automatically assign incremental values in order to other members.
enum Categories { Electronics, // 0 Food, // 1 Automotive = 6, // 6 Arts, // 7 BeautyCare, // 8 Fashion // 9 }
You can even assign different values to each member.
enum Categories { Electronics = 1, Food = 5, Automotive = 6, Arts = 10, BeautyCare = 11, Fashion = 15, WomanFashion = 15 }
Enumerations can be of any numeric data type, such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, enumerations cannot be of string type.
Specify the type after the enum name as :type. Below is defined a byte enum.
enum Categories: byte { Electronics = 1, Food = 5, Automotive = 6, Arts = 10, BeautyCare = 11, Fashion = 15 }
You can use dot notation: enum.member to access enumeration
enum WeekDays { Monday Tuesday Wednesday Thursday, Friday, Saturday, Sunday } Console.WriteLine(WeekDays.Monday); // Monday Console.WriteLine(WeekDays.Tuesday); // Tuesday Console.WriteLine(WeekDays.Wednesday); // Wednesday Console.WriteLine(WeekDays.Thursday); // Thursday Console.WriteLine(WeekDays.Friday); // Friday Console.WriteLine(WeekDays.Saturday); // Saturday Console.WriteLine(WeekDays.Sunday); // Sunday
Explicit casting is required to convert from enumeration type to its base integer type.
enum WeekDays { Monday Tuesday Wednesday Thursday, Friday, Saturday, Sunday } Console.WriteLine(WeekDays.Friday); //Output: Friday int day = (int) WeekDays.Friday; // Conversion from enum to int Console.WriteLine(day); //Output:4 var wd = (WeekDays) 5; // Conversion from int to enum Console.WriteLine(wd);//Output: Saturday
enum is an abstract class.