Create list of enums and pass it to a method
Solution 1
You can't specify generic argument type at runtime (well, without reflection). So, simply create non-generic method, which accepts argument of Type
type:
public static Dictionary<int, string> getDictionaryFromEnum(Type enumType)
{
return Enum.GetValues(enumType).Cast<object>()
.ToDictionary(x => (int)x, x => x.ToString());
}
Usage:
List<Type> enumsToConvertList = new List<Type>();
enumsToConvertList.Add(typeof(_myEnum1));
enumsToConvertList.Add(typeof(_myEnum2));
var a = getDictionaryFromEnum(enumsToConvertList[0]);
Solution 2
Why can't I call this?
In that case, you're passing in System.Type
, which is different than the generic specifier, which is a compile time value.
Solution 3
Here is an alternate method that takes the Enum as a generic and returns a dictionary of all the members
public static Dictionary<int, string> ToDictionary<T>()
{
var type = typeof (T);
if (!type.IsEnum) throw new ArgumentException("Only Enum types allowed");
return Enum.GetValues(type).Cast<Enum>().ToDictionary(value => (int) Enum.Parse(type, value.ToString()), value => value.ToString());
}
malber
Updated on June 07, 2022Comments
-
malber almost 2 years
I created a method which takes an enum and transforms it in a Dictionary where each int is associated with the name (as string) of the enum
// Define like this public static Dictionary<int, string> getDictionaryFromEnum<T>() { List<T> commandList = Enum.GetValues(typeof(T)).Cast<T>().ToList(); Dictionary<int, string> finalList = new Dictionary<int, string>(); foreach (T command in commandList) { finalList.Add((int)(object)command, command.ToString()); } return finalList; }
(ps. yes, I have a double cast but the application is meant to be a very cheap-and-dirty C#-enum to Javascript-enum converter).
This can be easily used like this
private enum _myEnum1 { one = 1001, two = 1002 }; private enum _myEnum2 { one = 2001, two = 2002 }; // ... var a = getDictionaryFromEnum<_myEnum1>(); var b = getDictionaryFromEnum<_myEnum2>();
Now, I was wondering whether I could create a list of enums to use for a series of calls to iterate my calls.
This was in the original question: [Why can't I call this?]
What should I do to be able to create a call like this one?
List<Type> enumsToConvertList = new List<Type>(); enumsToConvertList.Add(typeof(_myEnum1)); enumsToConvertList.Add(typeof(_myEnum2)); // this'll be a loop var a = getDictionaryFromEnum<enumsToConvertList.ElementAt(0)>();
-
malber about 11 yearsThanks lazy, I'll accept your answer. And I'll remove the 'Advanced knowledge' from the C# slot on my CV.
-
Sergey Berezovskiy about 11 years@malber maybe you just need to read several articles about generics and Linq, instead of modifying your cv :)