C#: Enhance Enums using Extension Methods
Extension Methods are one of the coolest features that have been added in .NET 3.5. I’ve heard arguments that there is no reason to use them, and the only reason Microsoft added them is to enable the ability to buid LINQ. Well, I do not entirely agree with that statement; in fact, I have found a cool way to use Extension Methods to enhance the System.Enum object since it cannot be inherited. Even though Enum can not be inherited, it can be extended using Extension Methods.
Here’s some example code for a simple Enum that has a DescriptionAttribute applied to each of it’s values:
public enum LocalizationMarket
{
[Description("en-US")]
English = 1,
[Description("en-ES")]
Spanish = 2
}
And here’s the code to an Extension Method that extends the LocalizationMarket Enum with the ToDescriptionString() method that returns the DescriptionAttributes value:
public static class LocalizationMarketExtensions
{
public static string ToDescriptionString(this LocalizationMarket val)
{
DescriptionAttribute[] attributes = (DescriptionAttribute[])val.GetType().GetField(val.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : string.Empty;
}
}
The usage of this new method is really simple:
LocalizationMarket myLocal = LocalizationMarket.English;
// this will show "en-US" in the MessageBox that's shown
MessageBox.Show( myLocal.ToDescriptionString() );
Now one thing you must remember with using Extension Methods is you may not want to extend the System.Enum Type, but instead just extend the Enums you create only.
Related Posts
-
C#: Case-Insensitive String Contains Best Practices
18 Oct 2024 -
C#: Read Text and JSON File Contents into Variable in Memory
18 Jun 2024 -
How to Cast an Int to an Enum in C#
17 Jun 2024