0

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

J4N
  • 19,480
  • 39
  • 187
  • 340
  • I found these two answers already on SO - hope they help: http://stackoverflow.com/questions/7362532/get-the-type-for-a-object-declared-dynamic and http://stackoverflow.com/questions/1408120/how-to-call-generic-method-with-a-given-type-object . – Joel Gregory Feb 02 '15 at 11:03

1 Answers1

0

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?

Community
  • 1
  • 1
a.azemia
  • 304
  • 1
  • 6
  • Thank you very much for the part 1 of the question, this is what I was looking for. Regarding the part 2, is there a way to avoid the reflection? – J4N Feb 02 '15 at 12:20
  • If you do not want to use reflection, you can always use Linq/Lambda Expressions. There's an answer for how to do this @ http://stackoverflow.com/questions/2850265/calling-a-generic-method-using-lambda-expressions-and-a-type-only-known-at-runt – a.azemia Feb 02 '15 at 16:00
  • Nice. Is it more efficient with lambda expression? – J4N Feb 02 '15 at 16:10
  • Yes lambda expression is more efficient than reflection. Read http://stackoverflow.com/questions/4803272/in-c-is-expression-api-better-than-reflection – a.azemia Feb 02 '15 at 16:20