Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the dynamic keyword meant to be *only* used with dynamic languages?

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?

like image 442
John B Avatar asked Dec 06 '22 04:12

John B


1 Answers

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 reflection Invoke all the time). In particular, two strengths are:

  • calling into generic methods (MakeGenericMethod etc is just so painful)
  • calling operators

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.

like image 137
Marc Gravell Avatar answered Dec 28 '22 08:12

Marc Gravell