Search code examples
c#linqenumscountextension-methods

Count and ToList extension method for Enum?


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 !


Solution

  • 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