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.

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:

using Microsoft.AspNetCore.Mvc.RazorPages;

namespace PracticalLearning.Pages
{
    enum PropertyType { Unknown, SingleFamily, TownHouse, Condominium }
        
    public class EnumerationsModel : PageModel
    {
        public void OnGet()
        {
        }
    }
}

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:

using Microsoft.AspNetCore.Mvc.RazorPages;

namespace PracticalLearning.Pages
{
    private enum PropertyType { Unknown, SingleFamily, TownHouse, Condominium }

    public class EnumerationsModel : PageModel
    {
        public void OnGet()
        {
        }
    }
}

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:

using Microsoft.AspNetCore.Mvc.RazorPages;

namespace PracticalLearning.Pages
{
    public class EnumerationsModel : PageModel
    {
        private enum Alignment
        {
            FarLeft,
            Left,
            CenterLeft,
            Center,
            CenterRight,
            Right,
            FarRight
        }

        public void OnGet()
        {
        }
    }
}

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:

@page
@model PracticalLearning.Pages.EnumerationsModel
@{
    PropertyType type;
}

@functions{
    enum PropertyType { Unknown, SingleFamily, TownHouse, Condominium }
}

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 the enumeration 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:

@page
@model PracticalLearning.Pages.EnumerationsModel
@{
    PropertyType type;
}

@functions{
    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:

using Microsoft.AspNetCore.Mvc.RazorPages;

namespace PracticalLearning.Pages
{
    public class EnumerationsModel : PageModel
    {
        private enum Alignment
        {
            FarLeft,
            Left,
            CenterLeft,
            Center,
            CenterRight,
            Right,
            FarRight
        }

        public void OnGet()
        {
            Alignment policies = Alignment.Right;
        }
    }
}

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, if you are working in a razor page, create an HTML tab, type @ followed by the name of the variable. Here is an example:

@page
@model PracticalLearning.Pages.EnumerationsModel
@{
    PropertyType type = PropertyType.SingleFamily;
}

@functions{
    enum PropertyType { Unknown, SingleFamily, TownHouse, Condominium }

    public class RealEstate
    {
        PropertyType type;
    }
    
    public class Exercise
    {
        PropertyType category;
    }
}

<p>Property Type: @type</p>

This would produce:

Property Type: SingleFamily

Enumerations, Functions, 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:

@page
@model PracticalLearning.Pages.EnumerationsModel
@{
    
}

@functions{
    enum PropertyType { Unknown, SingleFamily, TownHouse, Condominium }

    public enum HouseType
    {
        Unknown,
        SingleFamily,
        TownHouse,
        Condominium
    }
    
    public class House
    {
        HouseType propertyType;
    }
}

A Function or Method that Returns an Enumeration

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

namespace PracticalLearning.Models
{
    enum Alignment
    {
        FarLeft,
        Left,
        CenterLeft,
        Center,
        CenterRight,
        Right,
        FarRight
    }
    
    public class PoliticalParty
    {
        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:

namespace PracticalLearning.Models
{
    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:

@page
@model PracticalLearning.Pages.EnumerationsModel
@{
    PropertyType type = PropertyType.Condominium;
}

@functions{
    enum PropertyType { Unknown, SingleFamily, TownHouse, Condominium }

    void Build(PropertyType prop)
    {
    }
}

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. 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:

@page
@model PracticalLearning.Pages.EnumerationsModel
@{
    RealEstate reside = new();

    reside.Type = PropertyType.SingleFamily;
}

@functions{
    public enum PropertyType { Unknown, SingleFamily, TownHouse, Condominium }
    
    public class RealEstate
    {
        PropertyType pt;
        
        public PropertyType Type
        {
            get
            {
                return pt;
            }
            set
            {
                pt = value;
            }
        }
    }
}

<p>Property Type: @reside.Type</p>

An Automatic Property

If the property doesn't need to process anything or to validate the values passed to it, you can 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; }
}

Switching an Enumeration

The switch operation supports values based on an enumeration. When creating the statement, you can pass an expression that holds the value of an enumeration. In the body of the switch clause, each case can represent one of the members of the enumeration. Here is an example:

@page
@model PracticalLearning.Pages.EnumerationsModel
@{
    double frequency = 0.00;
    double interestRate = 0.00;
    int periods = 42;

    double principal = 7248.95;

     /* Compound Frequencies
     * 1. Weekly
     * 2. Monthly
     * 3. Quaterly
     * 4. Semiannually
     * 5. Annually */

    CompoundFrequency compounding = CompoundFrequency.Monthly;

    switch (compounding)
    {
        case CompoundFrequency.Daily:
            interestRate = 8.95;
            frequency = 365.00;
            break;

        case CompoundFrequency.Weekly:
            frequency = 52.00;
            interestRate = 11.95;
            break;

        case CompoundFrequency.Monthly:
            frequency = 12.00;
            interestRate = 14.75;
            break;

        case CompoundFrequency.Quaterly:
            frequency = 4.00;
            interestRate = 18.85;
            break;

        case CompoundFrequency.Semiannually:
            frequency = 2.00;
            interestRate = 22.55;
            break;

        case CompoundFrequency.Annually:
            frequency = 1.00;
            interestRate = 26.25;
            break;
    }

    double iRate = interestRate / 100;
    double per = periods / frequency;
    double interestAmount = principal * iRate * per;

    string strInterestAmount = $"{interestAmount:f}";
    string strFutureValue    = $"{(principal + interestAmount):f}";
}

@functions{
    enum CompoundFrequency { Daily, Weekly, Monthly, Quaterly, Semiannually, Annually }
}

<pre>===============================
Simple Interest
-------------------------------
Principal:          @principal
Interest Rate:      @interestRate%
Periods:            @periods months 
-------------------------------
Interest Amount:    @strInterestAmount
Future Value:       @strFutureValue
===============================</pre>

This would produce:

===============================
Simple Interest
-------------------------------
Principal:          7248.95
Interest Rate:      14.75%
Periods:            42 months 
-------------------------------
Interest Amount:    3742.27
Future Value:       10991.22
===============================

Previous Copyright © 2001-2021, FunctionX Sunday 28 November 2021 Next