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;

public class Exercise
{
    static int 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.Clear();

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

        return 0;
    }
}

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.

Creating an Enumeration

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 of names in the C# language. The formula of creating an enumeration is:

enum Enumeration_Name {Item1, Item2, Item_n};

To create an enumeration, you can manually type the code. To use a code snippet, right-click where you want to add the enumeration and click Insert Snippet... Double-click Visual C#. In the list, double-click enum:

Enum

Here is an example of creating an enumeration:

using System;

public class Exercise
{
    enum HouseType { Unknown, SingleFamily, TownHouse, Condominium }
    
    static int Main()
    {
        return 0;
    }
}

Declaring an Enumeration Variable

After creating an enumeration, each member of the enumeration 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;

public class Exercise
{
    enum HouseType { Unknown, SingleFamily, TownHouse, Condominium }
    
    static int Main()
    {
        HouseType propType;

        return 0;
    }
}

Just as done with the other types, you can use the var keyword to declare a variable of an enumeration type.

Initializing an Enumeration Variable

After declaring a variable for an enumeration, 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;

public class Exercise
{
    enum HouseType { Unknown, SingleFamily, TownHouse, Condominium }
    
    static int Main()
    {
        var propType = HouseType.SingleFamily;

        return 0;
    }
}

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;

public class Exercise
{
    enum HouseType { Unknown, SingleFamily, TownHouse, Condominium }
    
    static int Main()
    {
        var propType = HouseType.SingleFamily;

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

        return 0;
    }
}

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, and so on. 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 specify 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;

public class Exercise
{
    enum HouseType { Unknown = 5, SingleFamily, TownHouse, Condominium }
    
    static int Main()
    {
        return 0;
    }
}

In this case, Unknown now would have a value of 5, SingleFamily would have a value of 6 because it follows a member whose value is 1 (thus 5 + 1 = 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;

public class Exercise
{
    enum HouseType { Unknown = 3, SingleFamily = 12, TownHouse, Condominium = 8 }
    
    static int Main()
    {
        return 0;
    }
}

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;

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

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

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 sections and 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);
    }
}

public class Exercise
{
    static int Main()
    {
        var propType = new House();
        propType.Display();
        Console.WriteLine();

        propType.propertyType = HouseType.SingleFamily;
        propType.Display();
        Console.WriteLine();

        return 0;
    }
}

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.

ApplicationApplication: Creating and Using Enumerations

  1. Access the Flower.cs file
  2. To create some enumerations, change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    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
        }
    
        public class Flower
        {
            public FlowerType typeOfFlower;
            public FlowerColor majorColor;
            public FlowerArrangement arrangement;
            public decimal unitPrice;
    
            public Flower()
            {
                typeOfFlower = FlowerType.Mixed;
                majorColor = FlowerColor.Mixed;
                arrangement = FlowerArrangement.Vase;
                unitPrice = 0.00M;
            }
            public Flower(FlowerType type)
            {
                typeOfFlower = type;
                majorColor = FlowerColor.Mixed;
                arrangement = FlowerArrangement.Vase;
                unitPrice = 0.00M;
            }
            public Flower(FlowerType type, FlowerColor color,
                    FlowerArrangement argn, decimal price)
            {
                typeOfFlower = type;
                majorColor = color;
                arrangement = argn;
                unitPrice = price;
            }
        }
    }
  3. Access the FlowerShop.cs file
  4. To use the enumerations, change the file as follows:
    using System;
    using FlowerShop1;
    
    public 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.typeOfFlower);
            Console.WriteLine("Flower Color: {0}", order.flowerOrder.majorColor);
            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("=======================");
        }
    
        public static int Main()
        {
            Console.Title = "Corner Stone Flower Shop";
            OrderProcessing flower = CreateFlowerOrder();
            Console.WriteLine();
    
            Console.Clear();
    
            ShowFlowerOrder(flower);
            
            System.Console.ReadKey();
            return 0;
        }
    }
  5. To execute the application, press Ctrl + F5 or, on the main menu, click Debug -> Build Without Debuggin. 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
  6. Press Enter
    =======================
    ==-=-=Flower Shop=-=-==
    -----------------------
    Flower Type:  LivePlant
    Flower Color: Lavender
    Arrangement:  Basket
    Price:        $35.95
    Quantity:     4
    Total Price:  $143.80
    =======================
  7. Close the DOS window and return to your programming environment

Passing an Enumeration as Argument

As mentioned already, once an enumeration has been created, it becomes a type. It can be passed as argument and/or it can be returned from a method.

You pass an enumeration as argument using the same approach of a normal data type. Here is an example:

public class Exercise
{
    private static void ShowHouse(HouseType propType)
    {

    }
}

In the same way, you can pass as many enumeration types as necessary. In the body of the procedure, you can use the enumeration or ignore it. When calling the procedure, pass an argument that holds a value of the type of enumeration. Here is an example:

using System;

public enum HouseType
{
    Unknown = 2,
    SingleFamily = 4,
    TownHouse = 6,
    Condominium = 8,
}

public class Exercise
{
    private static void ShowHouse(HouseType propType)
    {
        Console.WriteLine("Type of house: {0}", propType);
    }

    public static int Main()
    {
        HouseType ht;

        ht = HouseType.SingleFamily;
        ShowHouse(ht);

        Console.ReadKey();
        return 0;
    }
}

This would produce:

Type of house: SingleFamily
Press any key to continue . . .

You can also pass the argument as optional. When creating a method, use the assignment operator to specify that the argument has a default value and assign the desired member of the enumeration. When calling the method, you can pass, or omit passing, a value for the argument. Here is an example:

using System;

public enum HouseType
{
    Unknown = 2,
    SingleFamily = 4,
    TownHouse = 6,
    Condominium = 8,
}

public class Exercise
{
    private static void ShowHouse(HouseType propType = HouseType.Unknown)
    {
        Console.WriteLine("Type of house: {0}", propType);
    }

    public static int Main()
    {
        HouseType ht;

        ht = HouseType.SingleFamily;
        ShowHouse();
        return 0;
    }
}

This would produce:

Type of house: Unknown
Press any key to continue . . .

Returning an Enumeration From a Method

To create a method that returns an enumeration, specify its return type as the name of the enumeration. In the body of the enumeration, do whatever you have to do. Before exiting the method, make sure you return a value that is the type of the enumeration. Here is an example:

public class Exercise
{
    private HouseType SpecifyPropertyType()
    {
        HouseType pt;

        pt = HouseType.TownHouse;
        return pt;
    }
}

You can call a method that returns an enumeration type by using just its name. Otherwise, you can use its returned value. Here is an example:

using System;

public enum HouseType
{
    Unknown = 2,
    SingleFamily = 4,
    TownHouse = 6,
    Condominium = 8,
}

public class Exercise
{
    private static void ShowHouse(HouseType propType = HouseType.Unknown)
    {
        Console.WriteLine("Type of house: {0}", propType);
    }

    private static HouseType SpecifyPropertyType()
    {
        HouseType pt;

        pt = HouseType.TownHouse;
        return pt;
    }

    public static int Main()
    {
        HouseType ht;

        ht = SpecifyPropertyType();
        ShowHouse(ht);
        return 0;
    }
}

This would produce:

Type of house: TownHouse
Press any key to continue . . .
 
 

Home Copyright © 2010-2016, FunctionX