Enhancing Enum Handling in Spargine: Beyond Enums and into Versatility

In programming, Enums are frequently employed to encapsulate a set of related constants, enhancing readability and organization while mitigating the use of “magic numbers“. For some time, I’ve utilized Enums to present user-friendly names in dropdown menus and similar interfaces. Nevertheless, depending exclusively on Enum values to retrieve names from a database can result in performance drawbacks. I advise steering clear of this approach.

This article will highlight methods available in Spargine to make using Enums much easier. Additionally, I’ll demonstrate how to go beyond Enums to overcome their limitations.

Utilizing EnumHelper: Simplifying Enum Handling

The EnumHelper currently has one method, as described below.

GetValues()

The GetValues() method returns the names and values of an Enum, with two additional features. Here’s an example of how to use the method:

var result = EnumHelper.GetValues<RequestCacheLevel>();

The data is returned in a type called EnumValue. Here’s an example of how the results look:

EnumValue { Name = Default, Value = 0 },
EnumValue { Name = BypassCache, Value = 1 },
EnumValue { Name = CacheOnly, Value = 2 },
EnumValue { Name = CacheIfAvailable, Value = 3 },
EnumValue { Name = Revalidate, Value = 4 },
EnumValue { Name = Reload, Value = 5 },
EnumValue { Name = NoCacheNoStore, Value = 6 }

One of the options is called “fixNames“, which converts the names to proper text that you can use in dropdown boxes, etc. Here’s an example:

var result = EnumHelper.GetValues<HttpCacheAgeControl>(fixNames: true);

This is how the values appear:

EnumValue { Name = None, Value = 0 },
EnumValue { Name = Min Fresh, Value = 1 },
EnumValue { Name = Max Age, Value = 2 },
EnumValue { Name = Max Stale, Value = 3 },
EnumValue { Name = Max Age And Min Fresh, Value = 4 },
EnumValue { Name = Max Age And Max Stale, Value = 6 }

Another option is “useXmlNames,” which returns the same data as shown in the first example.

Harnessing the Power of EnumExtensions

Below are the available helper methods in EnumExtensions.

GetDescription()

One challenge with Enums is that the names usually do not represent what will be shown to the user. The remedy for this is to use EnumMemberAttribute, as shown below:

public enum CountryName
{
    [EnumMember(Value = "Afghanistan")]
    Afghanistan,

    [EnumMember(Value = "Aland Islands")]
    AlandIslands,
    
    // Code removed for brevity
}

With EnumMemberAttribute, you can assign a human-readable name of your choice. To facilitate retrieving this name, I’ve added the GetDescription() method. Here’s an example of how to use it:

return GetCountries().FirstOrDefault(p => p.Name == countryName.GetDescription());

GetItems()

The extension method GetItems() will return the names and values for an Enum. Here’s how to use it:

var result = TaskStatus.Canceled.GetItems();

Below is the result of this call:

(Created, 0),
(WaitingForActivation, 1),
(WaitingToRun, 2),
(Running, 3),
(WaitingForChildrenToComplete, 4),
(RanToCompletion, 5),
(Canceled, 6),
(Faulted, 7)

Parse()

The Parse() method searches an Enum for the item based on its name. Here’s an example of how to use it:

var result = "Canceled".Parse<TaskStatus>();

Go Beyond Enums

Back in 2021, Jimmy Bogard posted about how he uses a class called Enumeration to overcome some of the limitations of Enums. So, I added it to Spargine to make it easy to use. In Spargine, Enumeration is an abstract record. Below is how to implement it:

public record DateTimeFormat : Enumeration
{
    public static readonly DateTimeFormat FullDateLongTime = new(0, "F");
    
    public static readonly DateTimeFormat FullDateShortTime = new(1, "f");

    // Code removed for brevity
}

Here’s an example of how I test it with ToFormattedString():

var result = now.ToFormattedString(DateTimeFormat.FullDateLongTime);

Below is a list of the methods in Enumeration:

  • AbsoluteDifference(): Returns the difference between two enumeration values.
  • FromDisplayName<T>(): Returns an Enumeration based on its display name.
  • FromValue<T>(): Returns an Enumeration based on its value.
  • GetAll<T>(): Returns all the Enumeration values.

If you need to go beyond Enums, Enumeration will do the trick.

Summary

This article explored the usage of Enums in programming and addressed the pitfalls of relying solely on Enum values for human-readable names from databases due to potential performance issues. I introduced EnumHelper and EnumExtensions in Spargine, offering methods like GetValues() and GetDescription() to simplify Enum handling and enhance usability. Additionally, I discussed the Enumeration class as a solution to surpass Enum limitations, providing flexibility for custom names and methods like FromDisplayName<T>(). This approach extends Enum functionality, offering more versatility when Enum’s constraints are exceeded, as exemplified by its integration into Spargine.

Learn more about Spargine by going here:

I hope you’ll employ these methods in Spargine to simplify the usage of Enums. Feel free to leave your comments below.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.