Home

Enumerations

 

Introduction

Consider that, when creating a program for a real estate company that sells houses, you want the program to ask a customer the type of house that he or she wants to purchase and/or the type of garage that the desired house should have. Here is an example:

using System;

class Program
{
    static void Main()
    {
        int TypeOfHouse = 0;
        int TypeOfGarage = 0;

        Console.WriteLine("Enter the type of house you want to purchase");
        Console.WriteLine("1 - Single Family");
        Console.WriteLine("2 - Townhouse");
        Console.WriteLine("3 - Condominium");
        Console.Write("Your Choice: ");
        TypeOfHouse = int.Parse(Console.ReadLine());

        Console.WriteLine("Enter the type of garage you want");
        Console.WriteLine("0 - Doesn't matter");
        Console.WriteLine("1 - Interior");
        Console.WriteLine("2 - Exterior");
        Console.Write("Your Choice: ");
        TypeOfGarage = int.Parse(Console.ReadLine());

        Console.WriteLine("\nHouse Type: {0}", TypeOfHouse);
        Console.WriteLine("Garage Type:  {0}", TypeOfGarage);
    }
}

Here is an example of running the program:

Enter the type of house you want to purchase
1 - Single Family
2 - Townhouse
3 - Condominium
Your Choice: 3
Enter the type of garage you want
0 - Doesn't matter
1 - Interior
2 - Exterior
Your Choice: 1

House Type:  3
Garage Type: 1
Press any key to continue . . .

For such a program, the numbers can be vague. 1 can be considered a general number but, in our program, it can represent a Single Family house or an Interior type of garage. At the same time, our program uses the constant 1 in particular meaningful ways. To make it possible to give more meaning to a constant number, when the number can be made part of a series, C# allows you to create a type of list.

An enumeration is a series of constant integers that each has a specific position in the list and can be recognized by a meaningful name. Based on this, instead of just remembering that the constant 1 represents Single Family, you can create a list that has that type of house. In another list, instead of using 1 again, you can give it a name. Consequently, in each list, although the constant 1 would still be considered, at least it would mean something precise.

To create an enumeration, you use the enum keyword, followed by the name of the enumeration, followed by a name for each item of the list. The name of the enumerator and the name of each item of the list follows the rules we reviewed for names. The formula of creating an enumeration is:

enum Series_Name {Item1, Item2, Item_n};

Here is an example:

using System;

class Program
{
    enum HouseType { Unknown, SingleFamily, TownHouse, Condominium }
    
    static void Main()
    {
    }
}

Declaring an Enumeration Variable

After creating an enumeration, each member holds a value of a natural number, such as 0, 4, 12, 25, etc. In C#, an enumeration cannot hold character values (of type char). After creating an enumeration, you can declare a variable from it. Here is an example:

using System;

class Program
{
    enum HouseType { Unknown, SingleFamily, TownHouse, Condominium }
    
    static void Main()
    {
        HouseType propType;
    }
}

Initializing an Enumeration Variable

After declaring such a variable, to initialize it, specify which member of the enumeration would be assigned to the variable. You should only assign a known member of the enumeration. To do this, on the right side of the assignment operator, type the name of the enumeration, followed by the period operator, and followed by the member whose value you want to assign. Here is an example:

using System;

class Program
{
    enum HouseType { Unknown, SingleFamily, TownHouse, Condominium }
    
    static void Main()
    {
        HouseType propType = HouseType.SingleFamily;
    }
}

You can also find out what value the declared variable is currently holding. For example, you can display it on the console using Write() or WriteLine(). Here is an example:

using System;

class Program
{
    enum HouseType { Unknown, SingleFamily, TownHouse, Condominium }
    
    static void Main()
    {
        HouseType propType = HouseType.SingleFamily;

        Console.WriteLine("House Type:  {0}", propType);
    }
}

This would produce:

House Type:  SingleFamily
Press any key to continue . . .

An enumeration is in fact a list of numbers where each member of the list is identified with a name. By default, the first item of the list has a value of 0, the second has a value of 1, etc. For example, on the HouseType enumeration, Unknown has a value of 0 while Townhouse has a value of 2. These are the default values. If you don't want these values, you can explicitly define the value of one or each member of the list. Suppose you want the Unknown member in the above enumeration to have a value of 5. To do this, use the assignment operator "=" to give the desired value. The enumerator would be:

using System;

class Program
{
    enum HouseType { Unknown = 5, SingleFamily, TownHouse, Condominium }
    
    static void Main()
    {
    }
}

In this case, Unknown now would have a value of 5, SingleFamily would have a value of 6, Townhouse would have a value of 7, and Condominium would have a value of 8. You can also assign a value to more than one member of an enumeration. Here is an example:

using System;

class Program
{
    enum HouseType { Unknown = 3, SingleFamily = 12, TownHouse, Condominium = 8 }
    
    static void Main()
    {
    }
}

In this case, Townhouse would have a value of 13 because it follows SingleFamily that has a value of 12.

Enumerations Visibility

By default, if you create an enumeration the way we have proceeded so far, it would be available only in the project it belongs to. As done for a class, you can control an enumeration's accessibility outside of its project. This means that you can hide or make it visible outside of its project. To do this, you can precede it with the private or the public keyword. Here is an example:

using System;

class Program
{
    public enum HouseType
    {
        Unknown,
        SingleFamily,
        TownHouse,
        Condominium
    }
    
    static void Main()
    {
        HouseType propType = HouseType.SingleFamily;

        Console.WriteLine("House Type:  {0}", propType);
    }
}

An Enumeration as a Member Variable 

After creating an enumeration, you can use it as a data type to declare a variable. To create a field that is of an enumeration type, follow the same rules as done for the primitive types: the name of the enumeration, followed by the name of the variable, and followed by a semi-colon. Here is an example:

public enum HouseType
{
    Unknown,
    SingleFamily,
    TownHouse,
    Condominium
}

public class House
{
    HouseType PropertyType;
}

In the same way, you can declare as many enumeration variables as you want. After declaring the variable, to initialize it, assign it the desired member of the enumeration. Here is an example:

public enum HouseType
{
    Unknown,
    SingleFamily,
    TownHouse,
    Condominium
}

public class House
{
    HouseType PropertyType;

    public House()
    {
        PropertyType = HouseType.Unknown;
    }
}

Once the member variable has been initialized, you can use it as you see fit as we will learn and practice in future lessons. At a minimum, you can pass it to Write() or WriteLine() to display its value. Here is an example:

using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    TownHouse,
    Condominium
}

public class House
{
    public HouseType PropertyType;

    public House()
    {
        PropertyType = HouseType.Unknown;
    }

    public void Display()
    {
        Console.WriteLine("Property Type: {0}", PropertyType);
    }
}

class Program
{
    
    static void Main()
    {
        House propType = new House();
        propType.Display();
        Console.WriteLine();

        propType.PropertyType = HouseType.SingleFamily;
        propType.Display();
        Console.WriteLine();
    }
}

This would produce:

Property Type: Unknown

Property Type: SingleFamily

Press any key to continue . . .

Using it as normal data type, you can create a method that returns an enumeration. You can also pass an enumeration to a method as argument.

Practical LearningPractical Learning: Creating and Using Enumerations

  1. Access the Flower.cs file
  2. To create some enumerations, change the file as follows:
     
    using System;
    
    namespace FlowerShop1
    {
        public enum FlowerType
        {
            Roses = 1,
            Lilies,
            Daisies,
            Carnations,
            LivePlant,
            Mixed
        }
    
        public enum FlowerColor
        {
            Red = 1,
            White,
            Yellow,
            Pink,
            Orange,
            Blue,
            Lavender,
            Mixed
        }
    
        public enum FlowerArrangement
        {
            Bouquet = 1,
            Vase,
            Basket,
            Mixed
        }
    
        class Flower
        {
            public FlowerType Type;
            public FlowerColor Color;
            public FlowerArrangement Arrangement;
            public decimal UnitPrice;
    
            public Flower()
            {
                Type = FlowerType.Mixed;
                Color = FlowerColor.Mixed;
                Arrangement = FlowerArrangement.Vase;
                UnitPrice = 0.00M;
            }
            public Flower(FlowerType type)
            {
                Type = type;
                Color = FlowerColor.Mixed;
                Arrangement = FlowerArrangement.Vase;
                UnitPrice = 0.00M;
            }
            public Flower(FlowerType type, FlowerColor color,
                    FlowerArrangement argn, decimal price)
            {
                Type = type;
                Color = color;
                Arrangement = argn;
                UnitPrice = price;
            }
        }
    }
  3. Access the Program.cs file
  4. To use the enumerations, change the file as follows:
     
    using System;
    
    namespace FlowerShop1
    {
        class Program
        {
            private static OrderProcessing CreateFlowerOrder()
            {
                OrderProcessing order = new OrderProcessing();
                int type, color, qty;
                int arrangement;
                decimal price;
    
                Console.WriteLine("=======================");
                Console.WriteLine("==-=-=Flower Shop=-=-==");
                Console.WriteLine("-----------------------");
    
                Console.WriteLine("Enter the Type of Flower Order");
                Console.WriteLine("1. Roses");
                Console.WriteLine("2. Lilies");
                Console.WriteLine("3. Daisies");
                Console.WriteLine("4. Carnations");
                Console.WriteLine("5. Live Plant");
                Console.WriteLine("6. Mixed");
                Console.Write("Your Choice: ");
                type = int.Parse(Console.ReadLine());
    
                Console.WriteLine("Enter the Color");
                Console.WriteLine("1. Red");
                Console.WriteLine("2. White");
                Console.WriteLine("3. Yellow");
                Console.WriteLine("4. Pink");
                Console.WriteLine("5. Orange");
                Console.WriteLine("6. Blue");
                Console.WriteLine("7. Lavender");
                Console.WriteLine("8. Mixed");
                Console.Write("Your Choice: ");
                color = int.Parse(Console.ReadLine());
    
                Console.WriteLine("Enter the Type of Arrangement");
                Console.WriteLine("1. Bouquet");
                Console.WriteLine("2. Vase");
                Console.WriteLine("3. Basket");
                Console.WriteLine("4. Mixed");
                Console.Write("Your Choice: ");
                arrangement = int.Parse(Console.ReadLine());
    
                Console.Write("Enter the Unit Price: ");
                price = decimal.Parse(Console.ReadLine());
    
                Console.Write("Enter Quantity:       ");
                qty = int.Parse(Console.ReadLine());
    
                Flower flr = new Flower((FlowerType)type,
                                        (FlowerColor)color,
                                        (FlowerArrangement)arrangement,
                                        price);
                order.FlowerOrder = flr;
                order.Quantity = qty;
    
                return order;
            }
    
            private static void ShowFlowerOrder(OrderProcessing order)
            {
                Console.WriteLine("=======================");
                Console.WriteLine("==-=-=Flower Shop=-=-==");
                Console.WriteLine("-----------------------");
                Console.WriteLine("Flower Type:  {0}", order.FlowerOrder.Type);
                Console.WriteLine("Flower Color: {0}", order.FlowerOrder.Color);
          Console.WriteLine("Arrangement:  {0}", order.FlowerOrder.Arrangement);
          Console.WriteLine("Price:        {0:C}", order.FlowerOrder.UnitPrice);
                Console.WriteLine("Quantity:     {0}", order.Quantity);
                Console.WriteLine("Total Price:  {0:C}", order.GetTotalPrice());
                Console.WriteLine("=======================");
            }
    
            static void Main()
            {
                OrderProcessing flower = CreateFlowerOrder();
                Console.WriteLine();
    
                ShowFlowerOrder(flower);
                Console.WriteLine();
            }
        }
    }
  5. Execute the application and process an order. Here is an example:
     
    =======================
    ==-=-=Flower Shop=-=-==
    -----------------------
    Enter the Type of Flower Order
    1. Roses
    2. Lilies
    3. Daisies
    4. Carnations
    5. Live Plant
    6. Mixed
    Your Choice: 5
    Enter the Color
    1. Red
    2. White
    3. Yellow
    4. Pink
    5. Orange
    6. Blue
    7. Lavender
    8. Mixed
    Your Choice: 7
    Enter the Type of Arrangement
    1. Bouquet
    2. Vase
    3. Basket
    4. Mixed
    Your Choice: 3
    Enter the Unit Price: 35.95
    Enter Quantity:       4
    
    =======================
    ==-=-=Flower Shop=-=-==
    -----------------------
    Flower Type:  LivePlant
    Flower Color: Lavender
    Arrangement:  Basket
    Price:        $35.95
    Quantity:     4
    Total Price:  $143.80
    =======================
    
    Press any key to continue . . .
  6. Close the DOS window
 

Previous Copyright © 2006 FunctionX, Inc. Next