Use of Enum.GetValues give me a compilation error

87 Views Asked by At

I have this code to list the values of an enum:

Type myType1 = Type.GetType("QBFC16Lib.ENTxnType");

var enumList = Enum.GetValues(myType1)
     .Cast<myType1>()
     .Select(d => (d, (int)d))
     .ToList();

I receive a compilation error in .Cast(myType1). The error is: "myType1 is variable but is used as a type"

If instead of MyType1 I use QBFC16Lib.ENTxnType in both places it works perfetly.

How can modify the code to overcome that error?

1

There are 1 best solutions below

1
Guru Stron On BEST ANSWER

You don't. Generics in C# require type name to be passed to generic type parameter, not the instance of System.Type (basically generics are "resolved" at compile time, so you can't use them dynamically via System.Type instance without some kind of runtime compilation or reflection). If you want to use LINQ you can "workaround" with object (note that underlying values are already of "correct" type - Enum.GetValues(myType1).GetValue(0).GetType() == myType1 is true):

var enumList = Enum.GetValues(myType1)
     .OfType<object>()
     .Select(d => (d, (int)d))
     .ToList();

Note that this relies on that QBFC16Lib.ENTxnType has int as underlying type, i.e. the following will throw InvalidCastException exception:

var enumList = Enum.GetValues(typeof(MyEnum))
    .OfType<object>()
    .Select(d => (d, (int)d))
    .ToList();

enum MyEnum : byte
{
    None,
    One,
    Two
}