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 because it is explicit. 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 and create a new Console App that supports the .NET 8.0 (Long-Term Support) named Chemistry4
  2. To create a new folder, in the Solution Explorer, right-click Chemistry4 -> Add -> New Folder
  3. Type Models as the name of the folder
  4. In the Solution Explorer, right-click Models -> Add -> Class...
  5. Change the file name to Element
  6. Click Add
  7. Change the document and class as follows:
    namespace Chemistry4.Models
    {
        public class Element
        {
            internal string ElementName  { get; set; }
            internal string Symbol       { get; set; }
            internal int    AtomicNumber { get; set; }
            internal double AtomicWeight { get; set; }
    
            public Element()                 { }
            public Element(string symbol) => Symbol = symbol;
            public Element(int number)    => AtomicNumber = number;
    
            public Element(int number, string symbol, string name, double mass)
            {
                Symbol       = symbol;
                ElementName  = name;
                AtomicWeight = mass;
                AtomicNumber = number;
            }
        }
    }
  8. In the Solution Explorer, right-click Program.cs and click Rename
  9. Type PeriodicTable (to get PeriodicTable.cs) and press enter
  10. Read the text in the message box and press Enter twice (to accept the name and access the document)
  11. Click the PeriodicTable.cs tab and change the document as follows:
    using Chemistry4.Models
    using static System.Console;
    
    void Present(Element obj)
    {
        WriteLine("Chemistry");
        WriteLine("------------------------");
        WriteLine("Symbol:        " + obj.Symbol);
        WriteLine($"Atomic Number: {obj.AtomicNumber}");
        WriteLine("Element Name:  " + obj.ElementName);
        WriteLine($"Atomic Weight: " + obj.AtomicWeight);
        Write("========================");
    }
    
    Element Prepare()
    {
        Element h = new(1, "H", "Hydrogen", 1.008);
        Element he = new(2, "He", "Helium", 4.002602);
        Element li = new(3, "Li", "Lithium", 6.94);
        Element be = new(4, "Be", "Beryllium", 9.0121831);
        Element b = new(5, "B", "Boron", 10.81);
        Element c = new(name: "Carbon", mass: 12.011, symbol: "C", number: 6);
        Element n = new(7, "N", "Nitrogen", 14.007);
        Element o = new(8, "O", "Oxygen", 15.999);
    
        Element f = new Element(9);
        f.Symbol = "F";
        f.AtomicWeight = 18.998;
        f.ElementName = "Fluorine";
    
        Element ne = new Element("Ne");
        ne.AtomicNumber = 10;
        ne.AtomicWeight = 20.180;
        ne.ElementName = "Neon";
        Element na = new(11, "Na", "Sodium", 22.990);
        Element mg = new(12, "Mg", "Magnesium", 24.305);
        Element al = new() {Symbol = "Al", AtomicNumber = 13, ElementName = "Aluminium", AtomicWeight = 26.982};
        Element si = new(14, "Si", "Silicon", 28.085);
    
        return si;
    }
    
    PeriodicTable chem = new PeriodicTable();
    
    Element elm = chem.Prepare();
    
    chem.Present(elm);
  12. To execute, on the main menu, click Debug -> Start Without Debugging:
    Chemistry
    ------------------------
    Symbol:        Si
    Atomic Number: 14
    Element Name:  Silicon
    Atomic Weight: 28.085
    ========================
    Press any key to close this window . . .
  13. Close the window and return to your programming environment

Creating an Enumeration

To let you create an enumeration, the C# language provides a keyword named enum. Type it followed by the name of the enumeration. Add 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 }
}

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. Here is an example:

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

To make the code easy to read, especially if the enumeration contains many members, you can put each curly bracket on its own line, you can put all members on the same line, some members on the 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

A Variable of an Enumeration Type

After creating an enumeration, you can declare a variable from it. 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 }

    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.

Displaying the Value of an Enumeration

You can display a member of an enumeration to the user. To do that, pass it in the parentheses of Write() or Write(). Here are examples:

using static System.Console;

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

Alignment policies = Alignment.Right;

WriteLine(policies);

policies = Alignment.CenterLeft;
WriteLine("Alignment: {0}", policies);

policies = Alignment.FarRight;
WriteLine($"Affiliation: {policies}", policies);

Enumerations and Classes

A 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;
        }
    }
}

An Automatic Property

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; }
}

Practical LearningPractical Learning: Using an Enumeration

  1. Click the Element.cs tab and change its class as follows:
    namespace Chemistry4.Models
    {
        public enum Phase { Gas, Liquid, Solid, Unknown }
    
        public class Element
        {
            internal string ElementName  { get; set; }
            internal string Symbol       { get; set; }
            internal int    AtomicNumber { get; set; }
            internal double AtomicWeight { get; set; }
            internal Phase  Phase        { get; set; }
    
            public Element()                 { }
            public Element(string symbol) => Symbol = symbol;
            public Element(int number)    => AtomicNumber = number;
    
            public Element(int number, string symbol, string name, double mass, Phase phase)
            {
                ElementName  = name;
                AtomicWeight = mass;
                Phase        = phase;
                Symbol       = symbol;
                AtomicNumber = number;
            }
        }
    }
  2. Click the PeriodicTable.cs tab and the class as follows:
    using Chemistry4.Models
    using static System.Console;
    
    void Present(Element obj)
    {
        WriteLine("Chemistry");
        WriteLine("--------------------------");
        WriteLine("Symbol:        " + obj.Symbol);
        WriteLine($"Atomic Number: {obj.AtomicNumber}");
        WriteLine("Element Name:  " + obj.ElementName);
        WriteLine($"Atomic Weight: " + obj.AtomicWeight);
                WriteLine("Phase/State:   " + obj.Phase);
        Write("==========================");
    }
    
    Element Prepare()
    {
        Element h = new(1, "H", "Hydrogen", 1.008, Phase.Gas);
        Element he = new(2, "He", "Helium", 4.002602, Phase.Gas);
        Element li = new(3, "Li", "Lithium", 6.94, Phase.Solid);
        Element be = new(4, "Be", "Beryllium", 9.0121831, Phase.Solid);
        Element b = new(5, "B", "Boron", 10.81, Phase.Solid);
        Element c = new(name: "Carbon", mass: 12.011, symbol: "C", number: 6, phase: Phase.Solid);
        Element n = new(7, "N", "Nitrogen", 14.007, Phase.Gas);
        Element o = new(8, "O", "Oxygen", 15.999, Phase.Gas);
    
        Element f = new(9);
        f.Symbol = "F";
        f.AtomicWeight = 18.998;
        f.ElementName = "Fluorine";
        f.Phase = Phase.Gas;
    
        Element ne = new("Ne");
        ne.AtomicNumber = 10;
        ne.AtomicWeight = 20.180;
        ne.ElementName = "Neon";
        ne.Phase = Phase.Gas;
        Element na = new(11, "Na", "Sodium", 22.990, Phase.Solid);
        Element mg = new(12, "Mg", "Magnesium", 24.305, Phase.Solid);
        Element al = new() {Phase = Phase.Solid, Symbol = "Al", AtomicNumber = 13, ElementName = "Aluminium", AtomicWeight = 26.982 };
        Element si = new(14, "Si", "Silicon", 28.085, Phase.Solid);
        Element p = new() { Symbol = "P", AtomicWeight = 30.974, AtomicNumber = 15, ElementName = "Phosphorus", Phase = Phase.Solid };
    
        return p;
    }
    
    Element elm = chem.Prepare();
    
    Present(elm);
  3. To execute, on the main menu, click Debug -> Start Without Debugging:
    Chemistry
    --------------------------
    Symbol:        P
    Atomic Number: 15
    Element Name:  Phosphorus
    Atomic Weight: 30.974
    Phase/State:   Solid
    ==========================
    Press any key to close this window . . .
  4. Press T to close the window and return to your programming environment
  5. Close your programming environment

Previous Copyright © 2001-2024, FunctionX Saturday 28 April 2023 Next