Monday October 5th

Sunday October 4th

Friday October 2nd

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 the code to an Extension Method that extends the LocalizationMarket Enum with the ToDescriptionString() method that returns the DescriptionAttributes value for the given enum value.


I think I'd prefer this, it's far more reusable:

public static A GetAttribute<A>(this Enum @enum)
where A : Attribute
if (!@enum.GetType().IsEnum)
return null;
object[] attributes = @enum.GetType().GetField(@enum.ToString()).GetCustomAttributes(typeof(A), false);
return attributes.Length > 0 ? (A)attributes[0] : null;

Oh, we still do smilies in code? *sigh*

All this extension method stuff scares me. It is kind of like inventing your own language for a program. Not sure if that is a good idea. Interesting though

Commenting on Stories is limited for now and will open up to those recommended by the community. Learn how
Loading DotNetKicks...
brought to you by the Kicks Network