views:

68

answers:

2

What are the differences between System.Dynamic.ExpandoObject, System.Dynamic.DynamicObject and dynamic?

In which situations do you use these types?

+3  A: 

dynamic is a type declaration. I.e. dynamic x means the variable x has the type dynamic.

DynamicObject is a type that makes it easy to implement IDynamicMetaObjectProvider and thus override specific binding behavior for the type.

ExpandoObject is a type that acts like a property bag. I.e. you can add properties, methods and so forth to dynamic instances of this type at runtime.

Brian Rasmussen
`dynamic` is not an actual type... it's just a hint to tell the compiler to use late binding for this variable. `dynamic` variables are actually declared as `object` in MSIL
Thomas Levesque
@Thomas: from the compiler's point of view it is a type, but you're right that the runtime representation is that of Object. You'll find the statement "statically typed to be dynamic" in several MS presentations.
Brian Rasmussen
@Thomas: and the language spec says "C# 4.0 introduces a new static type called dynamic".
Brian Rasmussen
@Brian, indeed... But I think it's confusing to consider it as a type, since there is no inheritance relation with types like DynamicObject or ExpandoObject
Thomas Levesque
+5  A: 

The dynamic keyword is used to declare variables that should be late-bound.
If you want to use late binding, for any real or imagined type, you use the dynamic keyword and the compiler does the rest.

When you use the dynamic keyword to interact with a normal instance, the DLR performs late-bound calls to the instance's normal methods.

The IDynamicMetaObjectProvider interface allows a class to take control of its late-bound behavior.
When you use the dynamic keyword to interact with an IDynamicMetaObjectProvider implementation, the DLR calls the IDynamicMetaObjectProvider methods and the object itself decides what to do.

The ExpandoObject and DynamicObject classes are implementations of IDynamicMetaObjectProvider.

ExpandoObject is a simple class which allows you to add members to an instance and use them dynamically.
DynamicObject is a more advanced implementation which can be inherited to easily provide customized behavior.

SLaks