Monday, July 9, 2018

Getting Enum descriptions using C#

 
Continuing on the .Net series on this blog, today let's talk some best practices.

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 is to use a custom method like the below to access it. I also built it as an extension method so my access to that method is simplified:

Accessing my 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:

Conclusion

On this post you learned how to use the DescriptionAttribute class to decorate your enums with nice contextual descriptions, you also learned how to extend your entities to use it with a simple demo console application.

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

See Also

Why you should start using .Net Core
Package Management in .Net Core
Exporting Html to Pdf using only JavaScript
Importing CSVs with .Net Core and C#
Exporting a CSV generated in-memory in Asp.Net with C#
Building and Running Asp.Net Core apps on Linux
Asp.Net / Asp.Net Core: Generating views in the backend

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

References

The source for this post is available on GitHub.