I just read a chapter in a programming book about Dynamic types. Although they are quite neat I cant think of a single real world example where I would use them. Does anyone here actually use them and for what?

See my question f.e.: stackoverflow.com/questions/6883741/… - the difference between Jon's solutions for 4.0 and 3.5. What I needed it for was feeding business objects with data from parsed CSV, whose format I wouldn't know beforehand. It could be [id][name][category][id][category][name] or whatever, so I'd just recognize the type of the busines object that was needed and then used a generic class for assembling them, making sure that the 1st occurence of attribute X goes to the 1st instance of class Y, the 2nd - to the 2nd etc.
–
Konrad MorawskiAug 2 '11 at 8:37

3 Answers
3

I've used dynamic to evaluate logical expressions represented in an object graph, where using the dynamic keyword allowed me to largely ignore the types of the operands.

For example, if my expression graph was an arithmetic expression with a multiplication operator (e.g. 12 * 1.3), I would use dynamic to store the operands 12 and 1.3, and dynamic again to catch the result from the multiplication.

Without dynamic I would be forced to deal with concrete numeric types (int/long/decimal/float, etc...) and the resulting code bloat. My dynamic solution requires very little code and is much easier to grasp and maintain.

My initial idea was to turn my logical expressions into snippets of Python or Ruby, then run these snippets through IronPython or IronRuby to evaluate the result. It struck me all I required from Python or Ruby was their dynamic typing, so I was very happy to see that dynamic affords Python-like typing for C#.

@Ed: I mean, why are they all different types to start with? Where are they coming from? Is there not a risk here of dividing a decimal by a double and ending up with inaccuracies you didn't expect?
–
pdrAug 2 '11 at 14:03

@pdr: the real answer to your questions requires more space and time than I can provide right now. The quick answer is that most of the expression are user input, so it's the problem of user if expression produces inaccurate results or even fails to evaluate.
–
Ed JamesAug 3 '11 at 9:49

In addition to previous answers relating to dynamic languages, dynamic typing in C# also eases a lot of pain when doing COM interop - e.g. see this MSDN article , or scroll down to the bottom of this post on Chris Burrows' blog.

It's a framework, it isn't always about you. In the case of dynamic alot of the backing came from the need to support more dynamic languages in the CLR, such as F# or IronPython. The fact that it helps cut down on code in other ways is an added bonus.