Monday, July 9, 2018

Getting Enum descriptions using C#

Accessing Enum descriptions in C# isn't complicated. Let's review an elegant solution using extension methods and the built-in attribute.
 

Introduction

One programming data type that developers use (and should!) a lot are Enums. Enums are simple and when well utilized, they simplify the development making your code cleaner. In .Net, Enums exist in the System.Enum namespace. In this post we assume you know and work with enums already. if not, check this link out for a nice introduction.

But, a common question is: how to show relevant labels on UI elements that are associated to enums? There's different answers for that question that depend on which context your code is running. In this post we'll examine how to do it in C# in a console app - but it could be your backend, a windows service, a library, etc.

The DescriptionAttribute

The tip do do this the right way is making use of the DescriptionAttribute available on the System.ComponentModel.DescriptionAttribute namespace.

For example, below I have my Status enum that determines the possible statuses that my invoices may have:

From the above code you can see that I added some descriptions to the attribute's constructor. That's exactly what that attribute is for. But how do we access it?

The EnumHelper.GetDescription extension method

The solution consists in using the extension method below so my access to that method is simplified and less verbose:

Accessing the Enum Description

Now the easy part: just call GetDescription using your extension method to get that description attribute as a string:

Running on Windows

Here's it our code running on Windows:

Running on Linux

And, as a nice exercise, let's run it on Linux too. First, we need to run the dotnet publish command to build it:
Then, just run it on your Linux with dotnet EnumDescription.dll:

Final Thoughts

On this post you learned how to combine the use the DescriptionAttribute class and a C# extension method to decorate/access your enums with nice contextual descriptions. You also learned how to extend your entities to use it in a simple demo console application on Windows and Linux.

Remember that this technique can be used everywhere. Just use your creativity!

See Also

.NET Core and .NET merging as .NET 5.0
Creating a Ubuntu Desktop instance on Azure
Windows Subsystem for Linux, the best way to learn Linux on Windows
Copying data between Azure databases in 3 easy steps
Simplifying Razor logic with C# Local Functions in ASP.NET Core
Why you should start using .NET Core
Building and Running Asp.Net Core apps on LinuxGenerating views in the backend with ASP.Net and ASP.Net Core

For more posts on .Net Core, please click here.

References

The source for this post is available on GitHub.