Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumeration extension methods

In vs2008, is it possible to write an extension methods which would apply to any enumeration.

I know you can write extension methods against a specific enumeration, but I want to be able to every enumeration using a single extension method. Is this possible?

like image 466
Eric Haskins Avatar asked Nov 09 '08 22:11

Eric Haskins


People also ask

Can you add methods to enum?

You can use extension methods to add functionality specific to a particular enum type.

What is extension method with example?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

Can C# enums have methods?

C# Does not allow use of methods in enumerators as it is not a class based principle, but rather an 2 dimensional array with a string and value.

What is extension method in MVC?

What is extension method? Extension methods in C# are methods applied to some existing class and they look like regular instance methods. This way we can "extend" existing classes we cannot change. Perhaps the best example of extension methods are HtmlHelper extensions used in ASP.NET MVC.


1 Answers

Yes, just code against the base Enum type, e.g.

public static void Something(this Enum e) {     // code here } 

The down-side is you'll probably end up doing some quite nasty stuff like finding the real base type using Enum.GetUnderlyingType, casting, and going down different branches depending on what the base type of the enum is, but you can find some good uses for it (e.g. we have IsOneOf and IsCombinationOf methods that apply to all enums).

PS: Remember when writing the method that, although ill advised, you can use float and double as the base types for enums so you'll need some special cases for those as well as unsigned values.

like image 158
Greg Beech Avatar answered Sep 23 '22 02:09

Greg Beech