How can I use a dynamic as a generic?
This
var x = something not strongly typed;
callFunction<x>();
and this
dynamic x = something not strongly typed;
callFunction<x>();
both produce this error
Error 1 The type or namespace name 'x'
could not be found (are you missing a using directive or an assembly reference?)
What can I do to x to make it legitimate enough to be used in <x>?
You could use type inference to sort of trampoline the 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 ifxhad 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.