Monday, July 9, 2018

Getting Enum descriptions using C#

Accessing Enum descriptions isn't complicated. Let's review an elegant solution using attributes, and extension methods.
Photo by Emre Karataş on Unsplash

One programming data type that developers use a lot are Enums. Enums are simple and when well utilized, simplify the development making your code cleaner. In .NET, all Enums derive from System.Enum. In this post we assume you know and work with enums already. if not, check this link out for a nice introduction.

A common question I see is: how to build and access enum descriptions? 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 elegantly in C# by using attributes and extension methods. We will also demo it using a console app but the same concept could be used on your backend, a windows service, a library, etc.

DescriptionAttribute

The secret do do this the right way is using the DescriptionAttribute class. For illustration, let's assume that we have a Status Enum in our code that determines the possible statuses invoices in our system may have:

As you can see, the above code also used Description attribute to decorate each entry with a description string. That's exactly what that attribute is for. But how do we access the attribute value?

Accessing the description

With the descriptions added to our enums, let's see how to access their descriptions. For clarity and simplicity, I'd like to propose an extension method so that access to that method is centralized in one place and can be reused throughout our application:

Now to access your description, we just have to call the GetDescription extension method to get that attribute as a string. Note that on the example below, I'm also doing two interesting things:
  1. Overriding the ToString method so we can simply call (line 8)
  2. Using String Interpolation to simplify the formatting instead of String.Format (lines 8-11)

Building a sample tool

To finish off, let's build a simple .NET Core tool to practice the above code. Oh, and because we're using .NET Core, let's run it on Windows and on my beloved Fedora Linux.

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.

Conclusion

On this post we reviewed 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. Use your creativity!

Source Code

As always, the source code is available on GitHub.

See Also

About the Author

Bruno Hildenbrand      
Principal Architect, HildenCo Solutions.