Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

C#

Learn step by step



Enum

An enum is a value type with a set of related named constants often referred to as an enumerator list. The enum keyword is used to declare an enumeration. It is a primitive data type, which is user defined.
Enums type can be integer (float, int, byte, double etc.). But if you used beside int it has to be cast.
enum is used to create numeric constants in .NET framework. All member of enum are of enum type. There must be a numeric value for each enum type.
The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.
Syntax

enum Dow { Sat, Sun, Mon, Tue, Wed, Thu, Fri };

enum WeekDays
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}

class Demo
{
public static void Main()
{
System.Console.WriteLine(WeekDays.Sunday);
System.Console.WriteLine(WeekDays.Monday);
System.Console.WriteLine(WeekDays.Tuesday);
System.Console.WriteLine(WeekDays.Wednesday);
System.Console.WriteLine(WeekDays.Thursday);
System.Console.WriteLine(WeekDays.Friday);
System.Console.WriteLine(WeekDays.Saturday);
}
}

Output

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday


enum WeekDays
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}

class Demo
{
public static void Main()
{
System.Console.WriteLine((int)WeekDays.Sunday);
System.Console.WriteLine((int)WeekDays.Monday);
System.Console.WriteLine((int)WeekDays.Tuesday);
System.Console.WriteLine((int)WeekDays.Wednesday);
System.Console.WriteLine((int)WeekDays.Thursday);
System.Console.WriteLine((int)WeekDays.Friday);
System.Console.WriteLine((int)WeekDays.Saturday);
}
}

Output

0
1
2
3
4
5
6
Some points about enum

  • enums are enumerated data type in c#.
  • enums are not for end-user, they are meant for developers.
  • enums are strongly typed constant. They are strongly typed, i.e. an enum of one type may not be implicitly assigned to an enum of another type even though the underlying value of their members are the same.
  • Enumerations (enums) make your code much more readable and understandable.
  • enum values are fixed. enum can be displayed as a string and processed as an integer.
  • The default type is int, and the approved types are byte, sbyte, short, ushort, uint, long, and ulong.
  • Every enum type automatically derives from System.Enum and thus we can use System.Enum methods on enums.
  • Enums are value types and are created on the stack and not on the heap.



Related Videos