There are quite many places in my code where I need to loop through enum values to do something. So for the sake of simplicity and clarity, I would like to convert, for example, the following piece of code
foreach (string name in Enum.GetNames(typeof(myEnum)))
{
chart1.Series[$"Series{name}*"].Enabled = optParams[(myEnum)Enum.Parse(typeof(myEnum), name)];
}
into
typeof(myEnum).ForEach((name, value) =>
{
chart1.Series[$"Series{name}*"].Enabled = optParams[value];
});
I have tried this extension method:
public static void ForEach<T>(this T t, Action<string, T> action) where T : Enum
{
foreach (string name in Enum.GetNames(typeof(T)))
{
action(value, (T)Enum.Parse(typeof(T), name));
}
}
But when I call it as above, the compiler cannot recognize e
and so throws this error: CS1503 Argument 1: cannot convert from 'System.Type' to 'myEnum'
.
If I change the way I call it—this time to explicitly specify the type of T (twice?)—to
typeof(myEnum).ForEach<myEnum>((name, value) =>
{
chart1.Series[$"Series{name}*"].Enabled = optParams[value];
});
then the error will change to CS1929 'Type' does not contain a definition for 'ForEach'…
.
How can I fix this?
UPDATE: Putting @Tim's suggestion forward, I changed my extension method to
public static void ForEach<T>(this Type t, Action<string, T> action) where T : Enum
{
foreach (string name in Enum.GetNames(typeof(T)))
{
action(value, (T)Enum.Parse(typeof(T), name));
}
}
And it works like
typeof(myEnum).ForEach<myEnum>((name, value) =>
{
chart1.Series[$"Series{name}*"].Enabled = optParams[value];
});
The problem, however, as @Olivier pointed out, is that I have never used t
in my extension method. The extension method can be written as
public static void ForEach2<T>(this Type t, Action<string, T> action) where T : Enum
{
foreach (var value in Enum.GetValues(t))
{
action(Enum.GetName(t, value), (T)value);
}
}
but still have to be called in the format of typeof(myEnum).ForEach<myEnum>()
.
UPDATE2:
As @Olivier clarified, an extension method was not necessary here as it is not intended to call it upon an instance of an enum, and so it could be done using an ordinary static
method like below.
public static class Enums
{
public static void ForEach<T>(Action<string, T> action) where T : Enum
{
foreach (string name in Enum.GetNames(typeof(T)))
{
action(value, (T)Enum.Parse(typeof(T), name));
}
}
}
and then
Enums.ForEach<myEnum>((name, value) => {…});