How to maintain sequence using enum Flags attribute

Vishal Pathak
Abhima C# Programming
4 min readAug 19, 2023

--

Have you ever faced an issue where you want to have all the previous enum values from the current value but you ended up creating a new list to maintain the sequence? If yes, then you are at the right place 😉.

Photo by Ramakrishnan Nataraj on Unsplash

First of all let’s understand what is enum and then will go to the solution part.

Enum:-

An enum is a special “class” that represents a group of constants (unchangeable/read-only variables).

To create an enum, we can use the enum keyword (instead of class or interface), and separate the enum items with a comma.

Example:-

enum OrderStatus
{
Booked ,
Confirmed ,
Dispatched,
InTransit,
OutForDelivery,
Delivered

}

As you can see in the above example we have created a simple enum OrderStatus which is having comma separated constant values inside it.

Now, let’s see how we can use values of the enum OrderStatus .

Example:-

 public class OrderService
{

public enum OrderStatus
{
Booked,
Confirmed,
Dispatched,
InTransit,
OutForDelivery,
Delivered

}

public OrderStatus GetOrderStatus(int orderId)
{
Dictionary<int, OrderStatus> order = new Dictionary<int, OrderStatus>()
{
{1, OrderStatus.Booked },
{2, OrderStatus.Confirmed },
{3, OrderStatus.Dispatched },
{4, OrderStatus.InTransit },
{5, OrderStatus.OutForDelivery},
};

return order[orderId];


}



}

In above code we have added a class “OrderService” which has method “GetOrderStatus” to get the order status from the given order id.

public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;

public Worker(ILogger<Worker> logger)
{
_logger = logger;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (!stoppingToken.IsCancellationRequested)
{
var orderObj = new OrderService();
var orderId = 1;
var status=orderObj.GetOrderStatus(orderId);
Console.WriteLine($"Current status of Order {orderId} is {status.ToString()}");
Console.ReadKey();
}
}
}

Output:-

Current status of Order 1 is Booked

Now in the above code we are calling “GetOrderStatus” method which will return the status of order id 1. After fetching the status of the order we are printing the value.

Now, let’s say you want all the previous status also to show the status history of the order. This cannot be achieved with the current code, let’s modify our code a little to make it work.

   public class OrderService
{
[Flags]
public enum OrderStatus:short
{
None = 0,
Booked = 1,
Confirmed = 2,
Dispatched = 4,
InTransit = 8,
OutForDelivery = 16,
Delivered = 32,

}

public OrderStatus GetOrderStatus(int orderId)
{
Dictionary<int, OrderStatus> order = new Dictionary<int, OrderStatus>()
{
{1, OrderStatus.Booked },
{2, OrderStatus.Confirmed },
{3, OrderStatus.Dispatched },
{4, OrderStatus.InTransit },
{5, OrderStatus.OutForDelivery},
};

return order[orderId];


}

public OrderStatus GetAllPreviousStatuses( OrderStatus orderStatus)
{
var currentStatus = ((int)orderStatus);
var previousStatus = currentStatus-1;
var previousstatuses = (OrderStatus)previousStatus;
return previousstatuses;
}



}

Here, we have modified the OrderStatus enum and added Flags Attribute to it. It will help us to have combination of values in enum object.

Then we have added new method GetAllPreviousStatuses which will return all the previous statuses of the current order status.

 protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (!stoppingToken.IsCancellationRequested)
{
var orderObj = new OrderService();
var orderId = 5;
var status=orderObj.GetOrderStatus(orderId);
Console.WriteLine($"Current status of Order:- {orderId} is {status.ToString()}");
var previousStatuses = orderObj.GetThePreviousStatuses(status);
Console.WriteLine($"All the Previous statuses are {previousStatuses.ToString()}");
Console.ReadKey();
}
}

Output:-

All the Previous statuses are Booked, Confirmed, Dispatched, InTransit

If you see the output, we are now getting all the previous statuses.

We have given order id as 5 which has OutForDelivery status and it has 16 as it’s integer value. Then we decreased it by 1 to get previous value. But here we don’t have any value assigned for 15 in the OrderStatus so now it will try to find all the combination that can be used as the status. Let’s see below calculation to know how the combinations are being calculated.

As you can see that this way we can maintain sequence through enum Flags attribute and without maintaining the sequence part at different place.

Thank you for reading please comment your suggestions, share the article, follow me and Abhima C# Programming publication.

Bhagavad Gita Chapter 9, Verse 18

गतिर्भर्ता प्रभु: साक्षी निवास: शरणं सुहृत् |
प्रभव: प्रलय: स्थानं निधानं बीजमव्ययम् || 18||

I am the Supreme Goal of all living beings, and I am also their Sustainer, Master, Witness, Abode, Shelter, and Friend. I am the Origin, End, and Resting Place of creation; I am the Repository and Eternal Seed.

--

--

Vishal Pathak
Abhima C# Programming

love ❤ coding, solving some industry problems technologies: JavaScript, C#, Angular, PLSQL, Docker Want to learn: Python, Go language, AI, ML and Cloud