Extension method on enumeration, not instance of enumeration

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().

Leave a Comment