0

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?

CBal
  • 21
  • 5
  • Right, you can't cast to a Type variable. It's a compile-type-vs-run-time thing. However, you can use `Convert.ChangeType`. I'll close this with a duplicate link you can check. – Tim Roberts Jun 30 '23 at 22:35
  • 1
    Does this answer your question? [Casting a variable using a Type variable](https://stackoverflow.com/questions/972636/casting-a-variable-using-a-type-variable) – Tim Roberts Jun 30 '23 at 22:35
  • 1
    @TimRoberts there is no need to cast or convert here, `Enum.GetValues` result is already of "correct" type. – Guru Stron Jun 30 '23 at 22:49
  • Have you considered using `Enum.GetValues()` https://learn.microsoft.com/en-us/dotnet/api/system.enum.getvalues?view=net-7.0#system-enum-getvalues-1 – Flydog57 Jul 01 '23 at 04:25

1 Answers1

1

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
}
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • May be you can help with another problem I got. When I tried to use that code in a library from QuickBooks SDK (QBFC16.lib) . I was receiving null in some enums and not in others in the line: Type myType1 = Type.GetType("QBFC16Lib.ENTxnType"). – CBal Jul 01 '23 at 19:09