638

The ExpandoObject class being added to .NET 4 allows you to arbitrarily set properties onto an object at runtime.

Are there any advantages to this over using a Dictionary<string, object>, or really even a Hashtable? As far as I can tell, this is nothing but a hash table that you can access with slightly more succinct syntax.

For example, why is this:

dynamic obj = new ExpandoObject();
obj.MyInt = 3;
obj.MyString = "Foo";
Console.WriteLine(obj.MyString);

Really better, or substantially different, than:

var obj = new Dictionary<string, object>();
obj["MyInt"] = 3;
obj["MyString"] = "Foo";

Console.WriteLine(obj["MyString"]);

What real advantages are gained by using ExpandoObject instead of just using an arbitrary dictionary type, other than not being obvious that you're using a type that's going to be determined at runtime.

0

10 Answers 10

756

Since I wrote the MSDN article you are referring to, I guess I have to answer this one.

First, I anticipated this question and that's why I wrote a blog post that shows a more or less real use case for ExpandoObject: Dynamic in C# 4.0: Introducing the ExpandoObject.

Shortly, ExpandoObject can help you create complex hierarchical objects. For example, imagine that you have a dictionary within a dictionary:

Dictionary<String, object> dict = new Dictionary<string, object>();
Dictionary<String, object> address = new Dictionary<string,object>();
dict["Address"] = address;
address["State"] = "WA";
Console.WriteLine(((Dictionary<string,object>)dict["Address"])["State"]);

The deeper the hierarchy, the uglier the code. With ExpandoObject, it stays elegant and readable.

dynamic expando = new ExpandoObject();
expando.Address = new ExpandoObject();
expando.Address.State = "WA";
Console.WriteLine(expando.Address.State);

Second, as was already pointed out, ExpandoObject implements INotifyPropertyChanged interface which gives you more control over properties than a dictionary.

Finally, you can add events to ExpandoObject like here:

class Program
{
   static void Main(string[] args)
   {
       dynamic d = new ExpandoObject();

       // Initialize the event to null (meaning no handlers)
       d.MyEvent = null;

       // Add some handlers
       d.MyEvent += new EventHandler(OnMyEvent);
       d.MyEvent += new EventHandler(OnMyEvent2);

       // Fire the event
       EventHandler e = d.MyEvent;

       e?.Invoke(d, new EventArgs());
   }

   static void OnMyEvent(object sender, EventArgs e)
   {
       Console.WriteLine("OnMyEvent fired by: {0}", sender);
   }

   static void OnMyEvent2(object sender, EventArgs e)
   {
       Console.WriteLine("OnMyEvent2 fired by: {0}", sender);
   }
}

Also, keep in mind that nothing is preventing you from accepting event arguments in a dynamic way. In other words, instead of using EventHandler, you can use EventHandler<dynamic> which would cause the second argument of the handler to be dynamic.

9
  • 20
    @AlexandraRusina, how does it know it's an event when you say d.MyEvent = null;, Or it doesn't? Feb 6, 2012 at 22:49
  • 1
    @Shimmy i think it's just a place holder for events or any type of property.
    – Jalal
    Jun 30, 2012 at 5:19
  • 22
    Maybe I'm missing something, but this is not event - this is a simple property of delegate type. Dec 23, 2012 at 22:08
  • 8
    The first block can be written using anonymous types: var expando = new { Address = new { State = "WA" } }; Console.WriteLine(expando.Address.State); I find this more readable but ymmv. And given it's statically typed, it's more useful in this context.
    – nawfal
    Oct 21, 2013 at 10:52
  • 17
    @nawfal thats not right - an anonymous is different to an Expando. You are creating an anonymous type, which can't then add arbitrary properties to.
    – politus
    Nov 11, 2014 at 12:07
79

One advantage is for binding scenarios. Data grids and property grids will pick up the dynamic properties via the TypeDescriptor system. In addition, WPF data binding will understand dynamic properties, so WPF controls can bind to an ExpandoObject more readily than a dictionary.

Interoperability with dynamic languages, which will be expecting DLR properties rather than dictionary entries, may also be a consideration in some scenarios.

2
  • 8
    It seems that databinding to dynamic objects is broken. The reporting user eisenbergeffect is here on SO and coordinator of caliburn.micro. @AlexandraRusina can you comment on the state of the bug and the status "Won't fix"
    – surfmuggle
    Mar 5, 2013 at 21:04
  • 2
    For those curious, I am currently able to bind to List<dynamic> and IEnumerable<dynamic> using WPF4 Dec 4, 2015 at 8:17
54

The real benefit for me is the totally effortless data binding from XAML:

public dynamic SomeData { get; set; }

...

SomeData.WhatEver = "Yo Man!";

...

 <TextBlock Text="{Binding SomeData.WhatEver}" />
1
  • Same for us using stubble as mustache templating.
    – StackHola
    Mar 17 at 15:54
33

Interop with other languages founded on the DLR is #1 reason I can think of. You can't pass them a Dictionary<string, object> as it's not an IDynamicMetaObjectProvider. Another added benefit is that it implements INotifyPropertyChanged which means in the databinding world of WPF it also has added benefits beyond what Dictionary<K,V> can provide you.

21

It's all about programmer convenience. I can imagine writing quick and dirty programs with this object.

0
15

I think it will have a syntactic benefit, since you'll no longer be "faking" dynamically added properties by using a dictionary.

That, and interop with dynamic languages I would think.

14

It's example from great MSDN article about using ExpandoObject for creating dynamic ad-hoc types for incoming structured data (i.e XML, Json).

We can also assign delegate to ExpandoObject's dynamic property:

dynamic person = new ExpandoObject();
person.FirstName = "Dino";
person.LastName = "Esposito";

person.GetFullName = (Func<String>)(() => { 
  return String.Format("{0}, {1}", 
    person.LastName, person.FirstName); 
});

var name = person.GetFullName();
Console.WriteLine(name);

Thus it allows us to inject some logic into dynamic object at runtime. Therefore, together with lambda expressions, closures, dynamic keyword and DynamicObject class, we can introduce some elements of functional programming into our C# code, which we knows from dynamic languages as like JavaScript or PHP.

4

There are some cases where this is handy. I'll use it for a Modularized shell for instance. Each module defines it's own Configuration Dialog databinded to it's settings. I provide it with an ExpandoObject as it's Datacontext and save the values in my configuration Storage. This way the Configuration Dialog writer just has to Bind to a Value and it's automatically created and saved. (And provided to the module for using these settings of course)

It' simply easier to use than an Dictionary. But everyone should be aware that internally it is just a Dictionary.

It's like LINQ just syntactic sugar, but it makes things easier sometimes.

So to answer your question directly: It's easier to write and easier to read. But technically it essentially is a Dictionary<string,object> (You can even cast it into one to list the values).

-1
var obj = new Dictionary<string, object>;
...
Console.WriteLine(obj["MyString"]);

I think that only works because everything has a ToString(), otherwise you'd have to know the type that it was and cast the 'object' to that type.


Some of these are useful more often than others, I'm trying to be thorough.

  1. It may be far more natural to access a collection, in this case what is effectively a "dictionary", using the more direct dot notation.

  2. It seems as if this could be used as a really nice Tuple. You can still call your members "Item1", "Item2" etc... but now you don't have to, it's also mutable, unlike a Tuple. This does have the huge drawback of lack of intellisense support.

  3. You may be uncomfortable with "member names as strings", as is the feel with the dictionary, you may feel it is too like "executing strings", and it may lead to naming conventions getting coded in, and dealing with working with morphemes and syllables when code is trying understand how to use members :-P

  4. Can you assign a value to an ExpandoObject itself or just it's members? Compare and contrast with dynamic/dynamic[], use whichever best suits your needs.

  5. I don't think dynamic/dynamic[] works in a foreach loop, you have to use var, but possibly you can use ExpandoObject.

  6. You cannot use dynamic as a data member in a class, perhaps because it's at least sort of like a keyword, hopefully you can with ExpandoObject.

  7. I expect it "is" an ExpandoObject, might be useful to label very generic things apart, with code that differentiates based on types where there is lots of dynamic stuff being used.


Be nice if you could drill down multiple levels at once.

var e = new ExpandoObject();
e.position.x = 5;
etc...

Thats not the best possible example, imagine elegant uses as appropriate in your own projects.

It's a shame you cannot have code build some of these and push the results to intellisense. I'm not sure how this would work though.

Be nice if they could have a value as well as members.

var fifteen = new ExpandoObject();
fifteen = 15;
fifteen.tens = 1;
fifteen.units = 5;
fifteen.ToString() = "fifteen";
etc...
-2

After valueTuples, what's the use of ExpandoObject class? this 6 lines code with ExpandoObject:

dynamic T = new ExpandoObject();
T.x = 1;
T.y = 2;
T.z = new ExpandoObject();
T.z.a = 3;
T.b= 4;

can be written in one line with tuples:

var T = (x: 1, y: 2, z: (a: 3, b: 4));

besides with tuple syntax you have strong type inference and intlisense support

4
  • 3
    Your examples are not identical in the sense that with value tuple, you cannot write T.c= 5; after finishing define T. With ExpandoObject you can do it because it's dynamic. Your example with value tuple is very identical with declaring anonymous type. E.g: var T2 = new { x = 1, y = 2, z = new { a = 3, b = 4 } };
    – LxL
    Feb 8, 2018 at 0:15
  • Why do I need to write T.c= 5 without defining it? ExpandoObject is only usefull when dealing with COM objects that are not defiend in .net. Otherwise, I neever use this ExpandoObject, because it is dirty and buggy in both design time and runtime. Feb 9, 2018 at 2:55
  • 1
    How about you have z at first assigned to (a:3,b:4) and then later you would like z to have additional c property? Can you do it with value tuple?
    – LxL
    Feb 9, 2018 at 8:11
  • 1
    So my point is that you cannot compare ExpandoObject with value tuple because they are designed for different purposes. By comparing your way, you dismissed the functionality which ExpandoObject is designed for, which is dynamic structure.
    – LxL
    Feb 9, 2018 at 8:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.