I attended Code Camp 12 recently, and a speaker there said that the new dynamic
keyword in C# 4.0 should only be used for interopping with dynamic languages. I think he also said that it is somewhat slow, compared to normal reflection (which itself is somewhat slow).
But then I heard Scott Hanselman mention that the dynamic keyword "makes reflection less painful".
So is it going to be acceptable to use the dynamic keyword for the purpose of reflecting an object that doesn't come from dynamic code?
I would say "no", but don't start using it insanely. Actually,
dynamic
is, from what I've benchmarked, faster than basic reflection, since it is keeping delegates (rather than using reflectionInvoke
all the time). In particular, two strengths are:MakeGenericMethod
etc is just so painful)However, there are using ways of doing what you need with interfaces etc;
dynamic
on a non-dynamic type really amounts to duck-typing. This is useful in a very limited set of scenarios; mostly: interfaces would be preferred. By don't rule them out.The downside of
dynamic
is that to be useful (without writing insane code) you need to know the names at compile-time; which often isn't the case, or we wouldn't be in this pickle! When you only know the name at runtime, there are other options (Expression
,Delegate.CreateDelegate
, "HyperDescriptor",DynamicMethod
, etc) of access the data in a fast way.