C#: Enhance Enums using Extension Methods (pietschsoft.com)

published 1 year, 6 months ago, submitted by crpietschmanncrpietschmann(11.1k) 1 year, 6 months ago

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.

3 comments | category: | Views: 543

tags: another

new Add a live kick counter to your blog >> liveImage

You can even customize the image by choosing your own colors, and then clicking the button below to update the preview and the html code:

  • "Kick It" text
  • "Kick It" background
  • kick count text
  • kick count background
  • border

Simply copy and paste this HTML into your blog post.


Users who kicked this story:

Comments:

posted by fquednaufquednau(395) 1 year, 6 months ago

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;
}

posted by fquednaufquednau(395) 1 year, 6 months ago

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

posted by samdnpsamdnp(970) 1 year, 6 months ago

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

information Login or create an account to comment on this story