0

I have a generic function:

 T GetVal<T>()
            where T : class;

I also have a function which gets a Type and based on it should return the type specified:

func(Type type) {
var classType = ? // get the class type from type to use it in the next line
   return GetVal<classType>()
}

Is it possible?

Ace
  • 831
  • 2
  • 8
  • 28
  • I looked at it before posting but unless I missed something there, I couldn't find something for my specific issue - I see there that he wants to call a generic method but I need to get the class itself to be used as the generic value – Ace Sep 10 '20 at 14:12
  • That's exactly what the approved answer there does - construct an invoke-able MethodInfo for a given generic method for a given Type. In `GetVal` - `classType` is a generic argument which `MakeGenericMethod` builds the method info for a generic method call specific to the given generic argument(s) provided. – asawyer Sep 10 '20 at 14:29
  • No that is not possible. You cannot use `GetVal()`. This is because `classType` is an instantiated class (an object), but you have to use the class. In your example this would be the `var` part of `var classType`. – chriga Sep 10 '20 at 14:44
  • Not sure what you mean @chriga, you can in fact call a generic method with any number of generic arguments / parameters where the types are not known until runtime via reflection. – asawyer Sep 10 '20 at 14:46
  • @asawyer sure, I know reflection. But with reflection you cannot resolve the specific example in the question. You can insert any code for the question mark and you will still not be able to use the expression `GetVal()`. `classType` in the return statement must be replaced by a concrete class: `GetVal()` (maybe `var` is `MyClass`). But I guess that was not the question. – chriga Sep 10 '20 at 15:00
  • @chriga Right, you wouldn't be able to use the compile time expression if the type is not known at compile time. That doesn't mean you can't invoke the method with a particular generic argument. It does mean you lose a measure of type safety. – asawyer Sep 10 '20 at 15:04

0 Answers0