An enumeration, or enumerator list, declares a series of related constants, each with an integer value. Enumerations are useful for defining sequences and states, particularly when there is a natural progression through those states. This is because each constant in the list can be formatted and compared using either its name or value.
An enum
is a special “class” that represents a group of constants (unchangeable/read-only variables).
To create an enum
, use the enum
keyword (instead of class or interface), and separate the enum items with a comma:
Why And When To Use Enums?
Use enums when you have values that you know aren’t going to change, like month days, days, colors, deck of cards, etc.
Advantages of using Enums
The advantage of the enum is to make the function easy to change the values for the future. It also reduces the error which are occured by the mistyping numbers.
Enums are not allocated in the memory they exist only in the compilation stage. Enum.parse throws an error if a value is incorrect. So we use Enum.IsDefined to check. So every helper method helps a enum a lot.
Example 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; namespace MyApplication { enum Level { Low, Medium, High } class Program { static void Main(string[] args) { Level myVar = Level.Medium; Console.WriteLine(myVar); } } } |
Output:
Medium
Example 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
using System; namespace MyApplication { class Program { enum Months { January, // 0 February, // 1 March, // 2 April, // 3 May, // 4 June, // 5 July // 6 } static void Main(string[] args) { int myNum = (int) Months.April; Console.WriteLine(myNum); } } } |
Output:
3
Example 3:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoApplication { class Program { enum Days{Sun,Mon,tue,Wed,thu,Fri,Sat}; static void Main(string[] args) { Console.Write(Days.Sun); Console.ReadKey(); } } } |
Output:
Sun
Example 4:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
using System; namespace MyApplication { class Program { enum Level { Low, Medium, High } static void Main(string[] args) { Level myVar = Level.Medium; switch(myVar) { case Level.Low: Console.WriteLine("Low level"); break; case Level.Medium: Console.WriteLine("Medium level"); break; case Level.High: Console.WriteLine("High level"); break; } } } } |
Output:
Medium level
Example 5:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Program { enum Month { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec } static void Main(string[] args) { Month mon = Month.Jan; for (int i = 0; i<=12; i++) { Console.WriteLine(mon++); } } } |
Output:
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec
12