Description:
- We can create our own set of named constants by using enumerations.
- Keyword enum is used to declare enumerations.
Syntax
enum name_of_enum {enumeration list };
Example
- class demo_enum
- {
- enum my_enum
- {
- a, b, c, d, e, f
- };
- public static void Main()
- {
- my_enum i;
- for (i = my_enum.a; i < my_enum.f; i++) Console.WriteLine(" {0}", i + " has value of: " + (int) i);
- Console.WriteLine();
- Console.ReadKey();
- }
- }
Output:
Some Rules for Enum - Initializing the enum member is not allow,
- enum Rules
- {
- a, b, c = d, d, e, f
- };
- public static void Main()
- {
- Rules i;
- for (i = Rules.a; i < Rules.f; i++) Console.WriteLine(" {0}", i + " has value of: " + (int) i);
- Console.WriteLine();
- Console.ReadKey();
- }
c = d is not allow
- Another variable declaration with same name is allow, but can’t create using new keyword.
- enum Rules
- {
- a, b, c, d, e, f
- };
- public static void Main()
- {
- int d = 2500;
-
- Rules i;
- for (i = Rules.a; i < Rules.f; i++)
- {
- Console.WriteLine(" {0}", i + " has value of: " + (int) i);
- Console.WriteLine();
- }
- Console.WriteLine(" variable d has value of: " + d);
- Console.ReadKey();
- }
new int e = 100; will get an error - A new expression requires
- Value of enum can’t increment directly,
- enum Rules
- {
- a, b, c, d, e, f
- };
- public static void Main()
- {
- a++;
- Rules i;
- for (i = Rules.a; i < Rules.f; i++)
- {
- Console.WriteLine(" {0}", i + " has value of: " + (int) i);
- Console.WriteLine();
- }
- Console.ReadKey();
- }
a++; will get an error – can’t change the value of constant
- Use of enum for initialization of another variable,
- enum Rules
- {
- a, b, c, d, e, f
- };
- public static void Main()
- {
- int z = Convert.ToInt16(Rules.b);
- Rules i;
- for (i = Rules.a; i < Rules.f; i++)
- {
- Console.WriteLine(" {0}", i + " has value of: " + (int) i);
- Console.WriteLine();
- }
- Console.WriteLine(" variable d has value of: " + z);
- Console.ReadKey();
- }
- Size of enum can be decide at the time time of declaration enum,
- enum Rules
- {
- a, b, c, d, e, f
- };
- enum short_values: short
- {
- B1 = 01, B2 = 02
- }
- enum long_values: long
- {
- A1 = 123456789985, A2 = 45678954123
- }
- public static void Main()
- {
- Rules i;
- Console.WriteLine(" size of enum Rules has value of : {0} ", sizeof(Rules));
- Console.WriteLine(" size of enum short_values has value of : {0} ", sizeof(short_values));
- Console.WriteLine(" size of enum long_values has value of : {0} ", sizeof(long_values));
- Console.ReadKey();
- }
Summary
This blog will help fresher candidates to understand enum in depth.