Thursday, March 28, 2013

How to create Enumerations in C#? [keyword: enum].


Enumeration are basically symbols that have fixed values. It is generally used in situations where we have to provide user with various fixed, per-defined choices or options. Let us consider an example of directions.

enum Directions{North, South, East, West};// syntax to declare an enum.

//Now creating an instance of Directions.
Directions D = Directions.East;
Console.WriteLine("{0}.", D); // Displays "East"

Thus the output is symbol itself rather than its value!

Given below is an example of a code implementing enum on a structure.
using System;
using System.Collections.Generic;
using System.Text;

namespace Enumerations
{
    class Program
    {

        static void Main(string[] args)
        {
            Employee E = new Employee("Shantanu", "Shirpure", 666,Employee.Genders.Male);
            Console.WriteLine(E.ToString());
            Console.ReadLine();
// if you dont use this command the console would compile and close immediately, and you wont be able to see the result.

        }

        struct Employee
        {
            public string firstName;
            public string lastName;
            public int id;
            public Genders gender;
            public Employee(string firstName, string lastName, int id, Genders gender) // this is a constructor.
            {

               //   firstName = firstName;
                this.firstName = firstName;
               // Here string firstName of struct Employee has scope
               //all through the methods hence to distinguish from parameters invoke this method.

                this.lastName = lastName;
                this.id = id;
               this.gender = gender;
            }


            public override string ToString() // this is a method.
            //override is a key word used to duplicate the systems method ToString with our own method
            //this is called as polymorphism
            {

                return firstName + " " + lastName + " (" + gender + "), ID " + id;

            }
           public enum Genders : int { Male, Female };
        }
    }
}


Conclusion:-

Enums therefore improve the code readability by providing symbols for set of values.

1 comment:

Anonymous said...
This comment has been removed by a blog administrator.