Fundamentals of Enumerations

Introduction

An enumeration is a group of names where each name holds a constant number (integer). The idea is that, instead of using meaningless numbers, a name represents a number and the name is more meaningful. To use this group of constant integers, you must create or use a group called an enumeration that itself has a name.

Practical LearningPractical Learning: Introducing Enumerations

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> New -> Project...
  3. In the middle list, click ASP.NET Web Application (.NET Framework) and set the project Name to Chemistry05
  4. Click OK
  5. In the New ASP.NET Web Application, make sure Empty is selected and click OK
  6. In the Solution Explorer, right-click Chemistry05 -> Add -> New Folder
  7. Type Content and press Enter
  8. In the Solution Explorer, right-click Content -> Add -> New Item...
  9. In the left frame of the Add New Item dialog box, click Style Sheet
  10. Change the file Name to Site
  11. Press Enter
  12. Create some styles as follows:
    body {
        margin: 0;
        background-color: #FFFFFF;
    }
    
    #top-banner {
        top: 0;
        width: 100%;
        height: 60px;
        position: fixed;
        background-color: #003366;
        border-bottom: 5px solid black;
    }
    
    .title-holder {
        top: 65px;
        width: 100%;
        height: 34px;
        position: fixed;
    }
    
    .container {
        width: 300px;
        margin: auto;
        padding-top: 120px;
    }
    
    #main-title {
        font-weight: 800;
        margin-top: 16px;
        font-size: 2.12em;
        text-align: center;
        color: antiquewhite;
        font-family: Garamond, 'Times New Roman', Georgia, serif
    }
    
    #sub-title {
        color: navy;
        font-weight: 600;
        padding-top: 2px;
        font-size: 1.68em;
        text-align: center;
        font-family: Garamond, 'Times New Roman', Georgia, serif
    }
    
    .emphasize { font-weight: bold; }
    .left-col  { width: 120px; }
  13. In the Solution Explorer, right-click Chemistry05 -> Add -> Add ASP.NET Folder -> App_Code
  14. In the Solution Explorer, right-click App_Code -> Add -> Class...
  15. In the middle list, make sure Class is selected.
    Change the file Name to Element
  16. Click Add
  17. Type code as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace Chemistry05.App_Code
    {
        public class Element
        {
            public string Symbol { get; set; }
            public string ElementName { get; set; }
            public int AtomicNumber { get; set; }
            public double AtomicWeight { get; set; }
    
            public Element(int number)
            {
                AtomicNumber = number;
            }
    
            public Element(string symbol)
            {
                Symbol = symbol;
            }
    
            public Element(int number, string symbol, string name, double mass)
            {
                Symbol = symbol;
                ElementName = name;
                AtomicWeight = mass;
                AtomicNumber = number;
            }
        }
    }

Creating an Enumeration

To create an enumeration, you use the enum keyword, followed by the name of the enumeration, and a body delimited by curly brackets. In the body of the enumeration, create the list of members where each member has a specific name. Therefore, the formula to create an enumeration is:

access-level enum Enumeration_Name { member1, member2, member_n }

Like a class, an enumeration can use an access level (private, public, or internal) to indicate its scope. The name of the enumeration follows the rules and suggestions of the names of classes. That name is followed by the body of the enumeration that contains the name of each item or member. The names of the members or items follow the rules and suggestions of the names of classes. To manually create an enumeration, type its code. Here is an example:

public class RealEstate
{
    enum PropertyType { Unknown, SingleFamily, TownHouse, Condominium }
}

To make the code easy to read, especially if the enumeration contains many members, you can put each curcly bracket on its own line, you can put all members on the same line, some members on same lines, or each member on its own line. Here is an example:

public class PoliticalParty
{
    private enum Alignment
    {
        FarLeft,
        Left,
        CenterLeft,
        Center,
        CenterRight,
        Right,
        FarRight
    }
}

If you are working from Microsoft Visual Studio, 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

Practical LearningPractical Learning: Creating an Enumeration

A Variable of an Enumeration Type

After creating an enumeration, you can declare a variable from it. An enumeration can be created inside (in the body of) a class or outside. If you are planning to use an enumeration from only one class, create it inside that class without specifying its access level or by applying private. Such an enumeration is considered private.

To declare a variable of an enumeration, use its name followed by a name for the variable. Here is an example:

public class RealEstate
{
    enum PropertyType { Unknown, SingleFamily, TownHouse, Condominium }

    public RealEstate()
    {
        
    }

    PropertyType type;
}

If you try using a private enumeration outside its class, you would receive an error. If you are planning to use an enumeration from more than one class, you can create it inside or outside a class. If you want to access an enumeration from more than one class, you can create it outside the class. Here is an example:

enum PropertyType { Unknown, SingleFamily, TownHouse, Condominium }

public class RealEstate
{
    PropertyType type;
}

public class Exercise
{
    PropertyType category;
}

In this case, you can optionally mark the enumeration as public or internal. You can also create the enumeration inside a class. In this case, you must apply the public or internal access level. To access such an enumeration, you must qualify it from the name of its class. Here are examples:

public class Management
{
    public enum PropertyType { Unknown, SingleFamily, TownHouse, Condominium }
}

public class RealEstate
{
    Management.PropertyType type;
}

public class Exercise
{
    Management.PropertyType category;
}

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 can only assign a member of the enumeration. To indicate the member you want, on the right side of the assignment operator, qualify the desired member from its enumeration. Here are examples:

public class PoliticalParty
{
    private enum Alignment
    {
        FarLeft,
        Left,
        CenterLeft,
        Center,
        CenterRight,
        Right,
        FarRight
    }

    // Blah blah blah

    Alignment policies = Alignment.Right;
}

public class Management
{
    public enum PropertyType { Unknown, SingleFamily, TownHouse, Condominium }
}

public class RealEstate
{
    Management.PropertyType type = Management.PropertyType.SingleFamily;
}

Just as done with the other types, you can use the var keyword to declare a variable of an enumeration type. This implies that you must immediately initialize the variable

Remember that you can get assistance from the Intellisence:

Initializing an Enumeration Variable

Accessing the Members of an Enumeration

There are various ways you can use an enumeration. One way is to find out what value the declared variable is currently holding.

Enumerations and Classes

An Field of an Enumeration Type

Once an enumeration exists, it becomes a type like any other. For example, you can create a field of an enumeration in a class. 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;
}

A Method that Returns an Enumeration

You can create a method that returns a member of an enumeration. When creating the method, type the name of the enumeration to the left of the name of the method. In the body of the method, do what you want. Before the closing curly bracket, return a member qualified from the name of the enumeration. Here is an example:

public class PoliticalParty
{
    private enum Alignment
    {
        FarLeft,
        Left,
        CenterLeft,
        Center,
        CenterRight,
        Right,
        FarRight
    }

    Alignment IndicateAbortionPrinciple()
    {
        Alignment choice = Alignment.CenterLeft;

        return choice;
    }
}

If you create a private enumeration (an enumeration created in the body of a class, as private or without an access level), only private methods that returns it can access that enumeration. A public method that returns an enumeration cannot access a private enumeration. As a result, the following code produces an error:

public class PoliticalParty
{
    private enum Alignment
    {
        FarLeft,
        Left,
        CenterLeft,
        Center,
        CenterRight,
        Right,
        FarRight
    }

    public Alignment IndicateAbortionPrinciple()
    {
        Alignment choice = Alignment.CenterLeft;

        return choice;
    }
}

Therefore, if you decide to create an enumeration inside a class, it may be a good idea to make it public because when a private method returns a public enumeration, there is no problem.

An Enumeration as Parameter

As mentioned already, once an enumeration has been created, it becomes a type. You can use an enumeration as a type for a parameter. You use the same approach of any data type. Here is an example:

public class PoliticalParty
{
    private enum Alignment
    {
        FarLeft,
        Left,
        CenterLeft,
        Center,
        CenterRight,
        Right,
        FarRight
    }

    void Abort(Alignment pregnancy)
    {

    }
}

A private method that uses a local enumeration can access it only if the enumeration is private. If a local enumeration is private, if a public method uses it as parameter, there would be an error. This means that the following code doesn't work:

public class PoliticalParty
{
    private enum Alignment
    {
        FarLeft,
        Left,
        CenterLeft,
        Center,
        CenterRight,
        Right,
        FarRight
    }

    public void Abort(Alignment pregnancy)
    {

    }
}

As mentioned previously, it may be a good idea to simply make your enumerations public.

An Enumerated Property

Since an enumeration is a data type, a property can be created from it. To create a property of an enumeration type, use the same steps as for a primitive data type. If you are planning to relay its value to a local field, the member variable must be the same type as the property. Here is an example:

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

public class RealEstate
{
    PropertyType pt;

    public RealEstate(PropertyType category)
    {
        pt = category;
    }

    public PropertyType Type
    {
        get
        {
            return pt;
        }
        set
        {
            pt = value;
        }
    }
}

If the property doesn't need to process anything or to valid the values passed to it, you can make create it as an automatic property. Here is an example:

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

public class RealEstate
{
    public RealEstate(PropertyType type)
    {
        Category = type;
    }

    public PropertyType Category { get; set; }
}

A static property of an enumeration type is created the same way, using the static keyword. Here are examples:

public enum Alignment
{
    FarLeft, Left, CenterLeft,
    Center,
    CenterRight, Right, FarRight
}

public class PoliticalParty
{
    private static Alignment align;

    static public Alignment Affiliation
    {
        get
        {
            return align;
        }

        set
        {
            align = value;
        }
    }

    public static Alignment Policy { get; set; }
}

Practical LearningPractical Learning: Using an Enumeration

  1. To create an enumerated property, change the class as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    public enum Phase
    {
        Gas,
        Liquid,
        Solid,
        Unknown
    }
    
    namespace Chemistry05.App_Code
    {
        public class Element
        {
            public string Symbol { get; set; }
            public string ElementName { get; set; }
            public int AtomicNumber { get; set; }
            public double AtomicWeight { get; set; }
            public Phase Phase         { get; set; }
    
            public Element(int number)
            {
                AtomicNumber = number;
            }
    
            public Element(string symbol)
            {
                Symbol = symbol;
            }
    
            public Element(int number, string symbol, string name, double mass)
            {
                Symbol = symbol;
                ElementName = name;
                AtomicWeight = mass;
                AtomicNumber = number;
            }
        }
    }
  2. In the Solution Explorer, click Chemistry05
  3. In the Solution Explorer, right-click Chemistry05 -> Add -> New Item...
  4. In the left list, expand Web and click Razor
  5. In the middle list, click Web Page (Razor v3)
  6. Change the name to Index
  7. Click Add
  8. Type the code as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Chemistry :: Magnesium</title>
    <link rel="stylesheet" type="text/css" href="~/Content/Site.css" />
    </head>
    <body>
    @{
        Chemistry05.App_Code.Element mg = new Chemistry05.App_Code.Element(12, "Mg", "Magnesium", 24.305);
    
        mg.Phase = Phase.Solid;
    }
    
    <div id="top-banner">
        <p id="main-title">Chemistry</p>
    </div>
    
    <div class="title-holder">
        <div id="sub-title">Magnesium</div>
        <hr />
    </div>
    
    <div class="container">
        <form name="frmChemistry" method="post">
            <table>
                <tr>
                    <td class="left-col emphasize">Symbol:</td>
                    <td><input type="text" name="txtSymbol" value="@mg.Symbol" /></td>
                </tr>
                <tr>
                    <td class="emphasize">Element Name:</td>
                    <td><input type="text" name="txtElementName" value="@mg.ElementName" /></td>
                </tr>
                <tr>
                    <td class="emphasize">Atomic Number:</td>
                    <td><input type="text" name="txtAtomicNumber" value="@mg.AtomicNumber" /></td>
                </tr>
                <tr>
                    <td class="emphasize">Atomic Weight:</td>
                    <td><input type="text" name="txtAtomicWeight" value="@mg.AtomicWeight" /></td>
                </tr>
                <tr>
                    <td class="emphasize">Phase:</td>
                    <td><input type="text" name="txtAtomicWeight" value="@mg.AtomicWeight" /></td>
                </tr>
            </table>
        </form>
    </div>
    </body>
    </html>
  9. To execute the application, on the main menu, click Debug -> Start Without Debugging:

    Using an Enumeration

  10. Close the browser and return to your programming environment

Fundamental Built-In Enumerations

Introductory to Built-In Enumerations

As mentioned in our introduction, enumerations provide a convenient way to name and identify constant values. As a result, the .NET Framework uses enumerations in all of its sub-libraries. In order to use an enumeration, you must know the library in which the enumeration is defined.

The Built-In Color Enumeration

To help you use colors in your applications, the .NET Framework provides an enumeration named Color. It is defined in the System.Drawing namespace. All of its members are easily recognizable names of colors such as Black, White, Red, Blue, Blue, Yellow, etc.

The Environment Class

Introduction

The .NET Framework provides a static class named Environment. This class quickly and easily gives some information about the application that is currently running and some objects you can use in your application. The Environment class is defined in the System namespace. This means that you don't have to do anything to access it, since it is automatically available whenever you create a C# application.

Getting the Machine Name

It used to be difficult to know the name of the computer on which your application is running. To let you easily get this information, the Environment class provides a property named MachineName.

Get the Operation System's Version

To assist you with knowing the version of the operating system on which the application is running, the Environment class provides the OSVersion property.

Getting the Current User's name

At any time, if you want to know the user name of the person who is currently using your application, you can get the value of the UserName property of the Environment class.

The Microsoft Windows operation system is usually installed on the C: drive with most of its drivers in a folder named System32 that is located either under Windows or WinNT. This full path of the driver's main folder is referred to as the system directory.

Getting the System Directory

To assist you with finding out the path to the system directory, the Environment class is equipped with a property named SystemDirectory.

Options on Using Enumerations: Enumerations and Combo Boxes

You can fill a combo box with the members of an enumeration. In this case, each member would become an item in the combo box.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2019, FunctionX Next