Enumerations: System System - Collections.Generic System - Text Consoleapplication15 (
Enumerations: System System - Collections.Generic System - Text Consoleapplication15 (
*) is a user defined integer type which provides way for attaching names to numbers there by increasing the flexibility of the code *) The enum keyword enumerates list of words by assigning them values 0,1,2,3 and so on *) it can also be said that a new data type defined will just be collection of constant variable names *) Syntax for enum is enum Shape { Circle, Square, Triangle } Or enum Shape{Circle,Square,Triangle} *) Here Circle has value 0,Square has value 1 and so on *) Variables are known as identifier and constant values attached with it is known as literals *) Both identifier and literal values can be accessed for any enum object in a program Example
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication15 { class Program { static void Main(string[] args) { X.Shape d = 0; Console.WriteLine((int)d); Console.WriteLine(d);
Console.WriteLine(b.area); Area c = new Area(); c.AreaShape(5, (Area.Shape)2); Console.WriteLine(c.area); Console.ReadKey(); } } class Area { public double area; public enum Shape { Circle, Square, Triangle } public void AreaShape(int t, Shape shape, int i = 15) { switch (shape) { case Shape.Circle: area = Math.PI * t * t; break; case Shape.Square: area = t * t; break; case Shape.Triangle: area = 0.5*t*i; break; default: Console.Write("Invalid input"); break;
} } } } Output:
Enumerator Initilaization
*) By default the value of first enum member is set to 0 and that of each subsequent member is incremented by 1 *) How ever one may specific value for different members for example: enum Shape { Circle=1, Square=3, Triangle=5 }
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication15 { class Program { static void Main(string[] args) { X.Shape d = X.Shape.Square; Console.WriteLine((int)d); Console.WriteLine(d); Console.WriteLine((X.Shape)5); Console.ReadKey(); }
Output:
*) We can use expression also as long as they use the already defined enum Member enum Shape { Circle=1, Square=Circle+2, Triangle=Circle+4 } *) Declarartion of enum member must not be circular enum Shape { Circle=1,
Console.ReadKey(); } } class X { public enum Shape:byte { Circle = 255, Square //will create compile time error
} } }
Practice Question: using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication15 { class Program { static void Main(string[] args) { X.Direction d = 0; int i = (int)d; Console.WriteLine(d); Console.WriteLine(i); X.Direction e = X.Direction.South; i = (int)e; Console.WriteLine(e); Console.WriteLine(i); X.Direction f = (X.Direction)10; i = (int)f; Console.WriteLine(f); Console.WriteLine(i); Console.ReadKey(); } } class X { public enum Direction { North, East=10, West, South
} } } Output: