tags:

views:

398

answers:

2

I don't understand, why use dynamic MethodBags when I can use ExpandoObject? What am I missing here?

+5  A: 

MethodBags and analogous implementations tend to have some limitations. It may be easier just to implement your own class if you find yourself running into these roadblocks. Specifically:

  • Hard to implement state in a method bag. (Expression trees cannot contain objects that are statically typed as dynamic; no good syntax to create methods that rely on internal state on the same dynamic object.)

  • Can only add public methods. No virtual, private, protected, or abstract methods.

  • Can't implement an interface.

In comparison, ExpandoObjects are true classes and are much richer and more full-featured. They more closely mimic what you'd otherwise get for free in, say, Ruby or Python.

John Feminella
Thanks. But I think you reversed my question. I was asking why use MethodBags when there's ExpandoObject, not why use ExpandoObject when I can use MethodBags.
stimpy77
@stimply77, methodbags are limited to certain level, as john stated you cannot use methodbgs where you wanted to implement intefaces and more specific types..
Ramesh Vel
@stimpy77: I think my point was more that there isn't much reason to, unless you absolutely don't need anything except a few methods. ExpandoObject seems like the better general-case choice.
John Feminella
I guess I just don't understand why MethodBag exists in the first place, when there's already ExpandoObject, and for that matter Dictionary<string, Delegate>. It seems like a communication breakdown in Redmond.
stimpy77
+2  A: 

Quick note: for those who don't know, dynamic method bag is a technique for adding methods dynamically to an object. Bill Wagner describes it here with source code here.


The simple answer is that the MethodBag concept is just showing you a technique. You can absolutely use the ExpandoObject to do this, but there may be a time when you want to write your own class that inherits from System.Dynamic.DynamicObject. An example of this might be to provide a dynamic JSON, YAML, or XML object that lets you reference your data in dot-properties-notation rather than in the traditional stringy ways. If you inherit from DynamicObject, you may find that you want to allow the addition of dynamic functions to your class too. The MethodBag technique shows you how to do that. The ExpandoObject is just one example of a class that implements this technique. ExpandoObject will be good for 95% of what you need, and the MethodBag technique shows you how to custom write your own when you decide to do that for the last 5%.

mattmc3