3

Is it possible de create a Count and a ToList extension method for an Enum instance ? I have tried this but don't know how to replace the "???", related to the type of the enum "e".

public static class EnumExtensions 
{ 
    public static int Count(this Enum e) 
    { 
        return Enum.GetNames(typeof(???)).Length; 
    } 

    public static List<???> ToList(this Enum e) 
    { 
        return Enum.GetValues(typeof(???)).Cast<???>().ToList(); 
    } 
}

Thanks a lot !

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Flash_Back
  • 565
  • 3
  • 8
  • 31
  • Your extension methods don't seem to make much sense from a client's point of view. `DayOfWeek.Monday.ToList()`? `DayOfWeek.Monday.Count()`? – dcastro Jan 13 '15 at 09:39

2 Answers2

3

Why do need new extension methods? You could use the available:

string[] dayNames = Enum.GetNames(typeof(DayOfWeek));
int count = dayNames.Count();
List<string> list = dayNames.ToList(); 

if you want a list of the enum-type:

List<DayOfWeek> list = Enum.GetValues(typeof(DayOfWeek)).Cast<DayOfWeek>().ToList();

An extension is pointless since you can extend only if you have an instance not a type. But you could use factory methods like this: https://stackoverflow.com/a/2422169/284240

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

You can use e.GetType() instead of typeof(???)

public static int Count(this Enum e) 
{ 
    return Enum.GetNames(e.GetType()).Length; 
} 

however, I don't think it will work as you expect as you cannot do this:

var shouldBe7 = DayOfWeek.Count(); // does not compile

but you can do

var shouldBe7 = DayOfWeek.Monday.Count(); // 7

It may be better to simply do:

public static class EnumHelper
{
    public static int Count(Type e)
    {
        // use reflection to check that e is an enum
        // or just wait for the Enum method to fail

        return Enum.GetNames(e).Length;
    }
}

which is then used as

var shouldBe7 = EnumHelper.Count(typeof(DayOfWeek)); // 7
dav_i
  • 27,509
  • 17
  • 104
  • 136