You could use type inference to sort of trampoline the call:
dynamic x = something not strongly typed;
CallFunctionWithInference(x);
...
static void CallFunctionWithInference<T>(T ignored)
{
CallFunction<T>();
}
static void CallFunction<T>()
{
// This is the method we really wanted to call
}
This will determine the type argument at execution time based on the execution-time type of the value of x
, using the same kind of type inference it would use if x
had that as its compile-time type. The parameter is only present to make type inference work.
Note that unlike Darin, I believe this is a useful technique - in exactly the same situations where pre-dynamic you'd end up calling the generic method with reflection. You can make this one part of the code dynamic, but keep the rest of the code (from the generic type on downwards) type-safe. It allows one step to be dynamic - just the single bit where you don't know the type.