Self-Describing ENUM Types on MVC application

For project download see link at end or article.

We are familiar with the use of enumerated type fields to provide category information.  For developers, the enum type may provide enough information to understand its meaning. However, it would be ideal if the enum type could be self-descriptive and provide a detail message of what it really means which can be achieved with the use of extension methods.

Let’s start by looking at this enum type declaration:

public enum EnumProjectType:int
Web =0,

We know the categories that are available, but let’s say that we would like to also show more information about each of one those entries. Web category is very general, so we would like to query it and ask more about what it contains. Let’s work on an extension method to see how we can extend this type to be more descriptive.

public static class EnumProjectTypeExtension
public static string Describe(this EnumProjectType type)
string content = type.ToString();       //default to the type
content = ResProjectType.ResourceManager.GetString(content, ResProjectType.Culture);
Trace.TraceInformation(String.Format("Message status {0} content {1}", type, content));
catch (Exception ex)
Trace.TraceError(String.Format("Message status {0} error {1}", type, ex.Message));

return content;

This extension method uses the enumerated type instance to call the Describe static method which provides more information about the category. Here we associate each category to a particular content, and we would also like to be flexible and allow for the content to change. For that, we can use a resource file and associate each category as a string resource with a more descriptive message. Look at the resource table below:

Category Description

We can now use the ResourceManager helper methods to look for that resource and load the value.

To show how that would work, we can quickly build a list with each enum category and corresponding description as follows:

//list of the categories
foreach (EnumProjectType type in EnumProjectType.GetValues(typeof(EnumProjectType)))
var item = new ProjectTypeItem()
Id = (int)type,
Description = type.Describe(),   //load the description
Tag = type.ToString()

The code just iterates the categories and calls the Describe extension method. We can then use this list and show the content on the web page as shown below:

Demo Application

We can now see that the enum type can tell us more about itself with the help of the extension method.   Since we are also using resource files, we can use localization of the resources to support other languages.

Well that is some descriptive enum type.

Demo Project Reference:

Available at:  GitHub  (see Dev Branch for latest changes)

Project Reference: og.samples.library.EnumTypes

Run And Select this option.

Run Demo