C#: 10-Enumerations/Enumerators

Given Original Code

Employee Class Field

public int Business; //index of the business name


 

Assignment

                    var emp = new Employee();

                    emp.Business = Util.EmployeeTrackerUtils.AskInt("Business Index Number: " +
                        "\n0:Apple \n1:Microsoft \n2:Samsung");
                    emp.Birthday = Util.EmployeeTrackerUtils.Ask("Employee Birthday: ");

Foreach

            foreach(var employee in employees)
            {
                switch (employee.Business)
                {
                    case 0:
                        Console.WriteLine("Exporting to Apple");
                        break;
                    case 1:
                        Console.WriteLine("Exporting to Microsoft");
                        break;
                    case 2:
                        Console.WriteLine("Exporting to Samsung");
                        break;
                    default:
                        break;
                }
            }


 

Enum can be used to clean things up

Employee Class Field

public Business Business; //index of the business name

Enum

    enum Business
    {
        Apple = 0,
        Microsoft = 1,
        Samsung = 2
    }

Assignment ( type cast int > enum)

                    var emp = new Employee();
                    emp.Business = (Business)Util.EmployeeTrackerUtils.AskInt("Business Index Number: " +
                        "\n0:Apple \n1:Microsoft \n2:Samsung");


 

Foreach

            foreach(var employee in employees)
            {
                switch (employee.Business)
                {
                    case Business.Apple:
                        Console.WriteLine("Exporting to Apple");
                        break;
                    case Business.Microsoft:
                        Console.WriteLine("Exporting to Microsoft");
                        break;
                    case Business.Samsung:
                        Console.WriteLine("Exporting to Samsung");
                        break;
                    default:
                        break;
                }
            }


 

Enums have inherent 'ordinals' based on their location in the enum assignment

    enum Business
    {
        Apple = 0,
        Microsoft = 1,
        Samsung = 2
    }


 

same as

    enum Business
    {
        Apple,
        Microsoft,
        Samsung
    }


 


 

Tags