Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !

like image 308
Flash_Back Avatar asked Feb 20 '26 00:02

Flash_Back


2 Answers

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

like image 162
Tim Schmelter Avatar answered Feb 22 '26 14:02

Tim Schmelter


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
like image 21
dav_i Avatar answered Feb 22 '26 13:02

dav_i



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!