Search code examples
c#genericsdynamic-dispatch

Dynamic object: Get the sub generic type and provide it to another method


I've a method, which receive basically a dynamic object. This is due to a dynamic dispatching, and it is not the point to discuss of why I've a dynamic input here.

I know that this dynamic object represent a type ASpecialClass<T> where T is unknown at the compilation time. Is there a way to extract the T type and give it to another method?

Like:

public void DoSomething(dynamic inputObject)//At this point, I know that it implements ASpecialClass<T>, but I don't know what is the T type
{
    extracType(InputObject);
    CallOtherMethod<With_the_extracted_Type>(inputObject);
}

There is two things here:

  1. Is there a way to extract the type T of the parameter?
  2. Is it possible to provide it back to another method, which is generic?

Thank you


Solution

  • Answer for question 1:

    static IEnumerable<Type> GetGenericTypeArgument(dynamic inputObject)
        {
            var genType = inputObject.GetType();
            return genType.GetGenericArguments();
        }
    

    Answer for question 2:

    You need to use reflection to invoke generic method by passing the generic argument provided in Answer 1. This has already been answered @ How do I use reflection to call a generic method?