Chapter 12

Enumerations

Enums are a data type in .NET Framework that can be used to hold enumerated values. You primarily use enums to restrict the possible values that can be assigned to a variable or returned from a method.

This chapter shines a light on this data type.

An Overview of Enum

You use the keyword enum to create a set of valid values for a field or a method. For example, the only possible values for the customerType field may be Individual and Organization. For the state field, valid values may be all the states in the US plus Canadian provinces. With enum, you can easily restrict your program to take only one of the valid values.

An enum type can stand alone or can be part of a class. You make it stand alone if it needs to be used in many places in your application. If it is only used from inside a class, the enum is better made part of the class.

As an example, consider the EmployeeType enum definition in Listing 12.1.

Listing 12.1: The EmployeeType enum

enum EmployeeType
{
    FullTime,
    PartTime,
    Permanent,
    Contractor
}

The EmployeeType enum has four enumerated values: FullTime, PartTime, Permanent, and Contractor. Enum values are case sensitive and by convention capitalized. Two enum values are separated by a comma and values can be written on a single line or multiple lines. The enum in Listing 12.1 is written in multiple lines to improve readability.

Using an enum is like using a class or an interface. For example, the code in Listing 12.2 uses the EmployeeType enum in Listing 12.1 as a field type.

Listing 12.2: Using the EmployeeType Enum

using System;
namespace EnumExample
{
    enum EmployeeType
    {
        FullTime,
        PartTime,
        Permanent,
        Contractor
    }

    class Employee
    {
        private EmployeeType employeeType;
        public Employee(EmployeeType employeeType)
        {
            this.employeeType = employeeType;
        }
        public String getDescription()
        {
            if (employeeType == EmployeeType.Contractor)
            {
                return "Contractor, pay on hourly basis";
            }
            else if (employeeType == EmployeeType.FullTime)
            {
                return "Permanent, salary-based";
            }
            else if (employeeType == EmployeeType.PartTime)
            {
                return "Part-Time, mostly students";
            }
            else
            {
                return "Full-Time, salary-based";
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            EmployeeType employeeType = EmployeeType.PartTime;
            Employee employee = new Employee(employeeType);
            Console.WriteLine(employeeType); // prints "PartTime"
            Console.WriteLine(employee.getDescription());
            Console.ReadKey();
        }
    }
}

In Listing 12.2, you use a value in an enum just like you would a class’s static member. For example, this code illustrates the use of EmployeeType.

EmployeeType employeeType = EmployeeType.PartTime;

Notice how the employeeType variable is assigned the enumerated value PartTime of the EmployeeType enum? Because the employeeType variable is of type EmployeeType, it can only be assigned a value defined in EmployeeType.

The use of enum at first glance is no difference than the use of constants. However, there are some basic differences between enums and constants. Constants are not a perfect solution for something that should accept only predefined values. For example, consider the CustomerTypeStaticFinals class in Listing 12.3.

Listing 12.3: Using constants

class CustomerTypeStaticFinals 
{
    public const int INDIVIDUAL = 1;
    public const int ORGANIZATION = 2;
}

Suppose you have a class named OldFashionedCustomer that uses an int for its customerType field. The following code creates an instance of OldFashionedCustomer and assigns a value to its customerType field:

OldFashionedCustomer ofCustomer = new OldFashionedCustomer();
ofCustomer.customerType = 5;

With constants there is nothing preventing you from assigning an invalid integer to customerType. To guarantee that a variable is assigned only a valid value, enums are better than constants.

Enums in a Class

You can use enums as members of a class. You use this approach if the enum is only used internally inside the class. For example, the code in Listing 12.4 is a modified version of the one in Listing 12.3. Unlike in Listing 12.3, the code in Listing 12.4 declares the EmployeeType enum as a field in the Employee class.

Listing 12.4: Using an enum as a class member

using System;

namespace EnumExample2
{
    class Employee
    {
        public enum EmployeeType
        {
            FullTime,
            PartTime,
            Permanent,
            Contractor
        }
        private EmployeeType employeeType;
        public Employee(EmployeeType employeeType)
        {
            this.employeeType = employeeType;
        }
        public String getDescription()
        {
            if (employeeType == EmployeeType.Contractor)
            {
                return "Contractor, pay on hourly basis";
            }
            else if (employeeType == EmployeeType.Permanent)
            {
                return "Permanent, salary-based";
            }
            else if (employeeType == EmployeeType.PartTime)
            {
                return "Part-Time, mostly students";
            }
            else
            {
                return "Full-Time, salary-based";
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Employee.EmployeeType employeeType =
                    Employee.EmployeeType.FullTime;
            Employee employee = new Employee(employeeType);
            Console.WriteLine(employeeType); // prints "FullTime"
            Console.WriteLine(employee.getDescription());
            Console.ReadKey();
        }
    }
}

Switching on enum

The switch statement can also work on enumerated values of an enum. The code in Listing 12.5 is an example of using an enum, DayOfWeek, in a switch statement.

Listing 12.5: Switching on enum

using System;

namespace EnumExample3
{
    enum DayOfWeek
    {
        Monday, Tuesday, Wednesday, Thursday, Friday, Saturday,
            Sunday
    }

    class Program
    {
        static void Main(string[] args)
        {
            DayOfWeek day = DayOfWeek.Sunday;
            switch (day)
            {
                case DayOfWeek.Monday:
                case DayOfWeek.Tuesday:
                case DayOfWeek.Wednesday:
                case DayOfWeek.Thursday:
                case DayOfWeek.Friday:
                    Console.WriteLine("Week day");
                    break;
                case DayOfWeek.Saturday:
                case DayOfWeek.Sunday:
                    Console.WriteLine("Week end");
                    break;
            }
            Console.ReadKey();
        }
    }
}

The switch statement in Listing 12.5 accepts a value in DayOfWeek. It will print “Week day” if the value is Monday, Tuesday, Wednesday, Thursday, or Friday. It will print “Week end” if the value is Saturday or Sunday.

Summary

C# supports enum, a special class that is a subclass of System.Enum. Enums are preferred over integers because they are more secure. You can also switch on an enum and iterate its values.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.104.238