0

Supposing I have:

public Dictionary<CertainEnum, Type> myDictionary = new()
{
    { CertainEnum.A, typeof(Class1) },
    { CertainEnum.B, typeof(Class2) }
}

How could I call a method that uses generics using this dictionary? I tried to declare 'testVariable' as either a 'Type' or 'dunamic', but the error is the same: 'testVariable is a variable but is is used like a type'.

public class MyClass<T>
{
    public List<T> MyMethod()
    {
        return new List<T>();
    }
}

dynamic testVariable = myDictionary[CertainEnum.A];
var result = MyClass.MyMethod<testVariable>();

By reading this extensive post:

How do I use reflection to call a generic method?

... what I was not able to find is how to deal with the fact that 'result' gets a List.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
roccaforte
  • 81
  • 5
  • You cannot use variables as generic type parameters, this includes `testVariable.GetType()`. – phuzi Jul 18 '22 at 11:24
  • 2
    `testVariable` will always reference an instance of `System.Type`. Using `dynamic` achieves nothing here, other than remove type safety. If you want to invoke `MyMethod` using a `System.Type` at runtime, you need to use reflection. – Johnathan Barclay Jul 18 '22 at 11:25
  • 2
    Generics are determined during compile time, but the value of `testVariable` is only known at runtime. You will need a non-generic overload of `MyMethod()` that takes the type as a parameter: `MyMethod(Type)`. – Good Night Nerd Pride Jul 18 '22 at 11:25
  • "what I was not able to find is how to deal with the fact that 'result' gets a List." why not? – Charlieface Jul 18 '22 at 13:19

0 Answers0