Adding metadata to Enums

A good enumeration in your C# code isn’t going to look like the values in your lookup table in your database and neither is it likely to have great descriptions of the items that you could display to your users. So how to extend the enumeration?

We’ve used attributes and called them EnumDescription (to distinguish it from the ComponentModel defined DescriptionAttribute) and EnumRepositoryValue. We then used extension methods on the enumeration values so they could easily display a good description or submit their equivalent value to the database.

One problem is that the .NET Enum type is not extensible so you can’t easily create a FromRepository() extension method without decorating the base Type. For translating database values to enums we created a helper method instead.

Now you can say this:


EnumMother enumMother =
    (EnumMother)EnumHelper.FromRepositoryValue(
        typeof(EnumMother),
        SomeEnumRepositoryValue);

And this:

string description = EnumMother.Some.GetDescription();

And this:

string repositoryValue = EnumMother.Some.ToRepositoryValue();

Given this:

    public enum EnumMother
    {
        [EnumDescription("Nothing at all")]
        [EnumRepositoryValue("N")]
        None = 0,

        [EnumDescription("Some of it")]
        [EnumRepositoryValue("S")]
        Some = 1,

        [EnumDescription("Everthing, ever")]
        [EnumRepositoryValue("A")]
        All
    }

A couple more extensions provide ToList() functionality as a bonus for creating user interface select lists.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s