Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension method on enumeration, not instance of enumeration

I have an enumeration for my Things like so:

public enum Things {    OneThing,    AnotherThing } 

I would like to write an extension method for this enumeration (similar to Prise's answer here) but while that method works on an instance of the enumeration, ala

Things thing; var list = thing.ToSelectList(); 

I would like it to work on the actual enumeration instead:

var list = Things.ToSelectList(); 

I could just do

var list = default(Things).ToSelectList(); 

But I don't like the look of that :)

I have gotten closer with the following extension method:

public static SelectList ToSelectList(this Type type) {    if (type.IsEnum)    {       var values = from Enum e in Enum.GetValues(type)                    select new { ID = e, Name = e.ToString() };       return new SelectList(values, "Id", "Name");    }    else    {       return null;    } } 

Used like so:

var list = typeof(Things).ToSelectList(); 

Can we do any better than that?

like image 354
Jamezor Avatar asked Mar 11 '10 02:03

Jamezor


People also ask

Can you use extension to add functionality to an enumeration?

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

Can extension methods be non static?

Actually I'm answering the question of why extension methods cannot work with static classes. The answer is because extension methods are compiled into static methods that cannot recieve a reference to a static class.

Can you extend an enum Swift?

We can extend the enum in two orthogonal directions: we can add new methods (or computed properties), or we can add new cases. Adding new methods won't break existing code. Adding a new case, however, will break any switch statement that doesn't have a default case.

Can an enum have methods C#?

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.


1 Answers

Extension methods only work on instances, so it can't be done, but with some well-chosen class/method names and generics, you can produce a result that looks just as good:

public class SelectList {     // Normal SelectList properties/methods go here      public static SelectList Of<T>()     {         Type t = typeof(T);         if (t.IsEnum)         {             var values = from Enum e in Enum.GetValues(type)                          select new { ID = e, Name = e.ToString() };             return new SelectList(values, "Id", "Name");         }         return null;     } } 

Then you can get your select list like this:

var list = SelectList.Of<Things>(); 

IMO this reads a lot better than Things.ToSelectList().

like image 88
Aaronaught Avatar answered Sep 21 '22 05:09

Aaronaught