How I Use Enums In My Practice

In my previous articles, while explaining some of the syntactic units of the C# language, I noted that the vast majority of books written in this language lack practical examples. This time, our topic will be about enums (enumerations) shown in C# language, which are easy from the technical point of view but weakly described from the practical point of view. I will try to show the place of enums in practice by bringing real code examples from several projects I have worked on so far.

Question 1. What is an enum?

Enums (Enumerations) - is used when enumerating any information. Enums are of type int by default with a value type. If the information to be listed does not digitally store more than 255 values, we display its type directly as bytes so that it does not take up additional space in the memory. If no number is specified in front of the listed data in the Enum, then the counting process starts from 0. In some cases, we have to enter those numbers manually.

namespace enums_in_practice {
    public enum RequestType: byte {
        HttpPost = 1,
            HttpGet = 2,
            HTTPPut = 3
    }
}

All enums are derived from a class called Enum by default. Enum class is an abstract class, but due to its "private", low-level character, it cannot be directly derived from that class.

How I use Enums in my practice

All the enums we create are derived directly from the Enum class.

using System;
using static System.Console;
namespace enums_in_practice {
    class Program {
        static void Main(string[] args) {
            //it is easy to convert enum to value types
            byte type = (byte) RequestType.HttpGet; //returns "2"
            //also via versa
            RequestType requestType = (RequestType) 2;
            //use GetNames() to retrieve names of enum values
            Array.ForEach(Enum.GetNames(typeof(RequestType)), x => WriteLine(x));
            //GetValues() helps to retrive values of enums as int values
            Array.ForEach((byte[]) Enum.GetValues(typeof(RequestType)), x => WriteLine(x));
            //Parse helps to parse enum to string
            RequestType fromString = (RequestType) Enum.Parse(typeof(RequestType), "3");
            // we dont have "5" so it returns false
            bool hasCurrentValue = Enum.IsDefined(typeof(RequestType), "5");
            ReadLine();
        }
    }
}

Now it is time to show real examples of Enums in some of the projects I've worked on and the pieces of the specification that require their use...

Where can enums be used in practice?

Use case 1

In one of the local bank integration projects I worked on, the technical task stated that the customer could perform the following transactions through the payment terminal:

1) Paying loans through customer code

2) Deposit to debit card

3) Loan payment with contract code

To meet the requirement, I created an enum like this:

public enum ReceiptType: byte {
    Customer_CreditCode_Credit = 1,
        Customer_Contact_Credit = 2,
        Customer_Debet = 3
}

In that system, separate text information was received for 2 types of payment. It was not possible to extract it to the Enum because when sending a request to the service, that text information was needed to show the type of payment. In some cases, when I encountered something like this, I used the static class because the Enum does not have a string option in C#. The goal was to collect the same texts that are repeated everywhere. It would be possible to perform the problem in a reflective form, but this would reduce the speed significantly.

public static class RequestType {
    public static string Accountcred = "Accountcred";
    public static string Account = "account";
}

Use case 2

To provide program progress based on the different responses from the server

In the Xbank project, if the response from the next service was "1", the user was found; otherwise, if it was "0", it meant that the user was not found. I implemented this with an enum.

public enum XBankResponse {
    Customer_Found = 1,
        Customer_Not_Found = 0
}

Use case 3

Say we're providing 3 types of courses on our site: Offline, Online, and video courses. For this, such an enum is formed:

namespace Brain2BrainWebApp.Models {
    public enum CourseType {
        VideoCourse,
        Online,
        Offline
    }
}

Use case 4

It is usually necessary to perform a logging process. The aspect of logging can vary from project to project. To implement the logging process in one of the projects, I wrote an enum to determine what type of logging is being done.

public enum LogOperationType: Byte {
    Inserted = 1,
        Updated = 2,
        Deleted = 3
}

Use case 5

To identify the type of operation performed on the database:

public enum ActionType {
    Delete = 2,
        Update = 1,
        Insert = 0
}

Use case 6

In one of the projects I wrote for company X, for the visiting delegation to be able to choose the type of food:

public enum MealType {
    Lunch = 2,
        Dinner = 3,
        Breakfast = 1
}

Use case 7

Another module of the same project was related to the mail system. If journalists want to participate in the competition, they should first apply through the website, fill out a form and wait for the response. I wrote the response types with an enum like this:

namespace AccreditationMS.Models.Domain {
    public enum MediaStatusType: byte {
        Investigating = 1,
            Rejected = 2,
            Accepted = 3
    }
}

Use case 8

To provide a role system in a project, reflect such a role system structure with an enum:

public enum Roletype: byte {
    SuperAdmin = 1 << 6,
        UEG = 1 << 5,
        LOC = 1 << 4,
        NF = 1 << 3,
        Group = 1 << 2,
        Individual = 1,
        Media = 1,
        MediaManager = 4,
        Observer = 2
}

Use case 9.

When determining the type of card:

public enum CardStatus {
    Deactive = 1,
        Active = 2
}

Use case 10

In one project, users with card-related problems could enter the system and open a ticket. To determine the status of that ticket:

public enum IncidentStatus {
    Open = 1,
        InProcess = 2,
        Close = 3,
}

Enum creation can vary depending on the requirement. Although I started the domain model as an enum in many projects, later, it was necessary to convert it to a database model. One of the questions I ask when determining whether a model is an enum or a database model is "If I need to change, should I do it in the database or the code?" has been Enum is not always a good option. If you know the "amount" of enumerated data throughout the project, you can safely use an enum if the number will not change.


Recommended Free Ebook
Similar Articles