640

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.

Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373

10 Answers10

761

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.

David Klempfner
  • 8,700
  • 20
  • 73
  • 153
Alexandra Rusina
  • 10,991
  • 2
  • 20
  • 16
  • 20
    @AlexandraRusina, how does it know it's an event when you say `d.MyEvent = null;`, Or it doesn't? – Shimmy Weitzhandler Feb 06 '12 at 22:49
  • 1
    @Shimmy i think it's just a place holder for events or any type of property. – Jalal Jun 30 '12 at 05:19
  • 22
    Maybe I'm missing something, but this is not event - this is a simple property of delegate type. – Sergey Berezovskiy Dec 23 '12 at 22:08
  • I believe it should be `MyDelegate` and not `MyEvent`. – Royi Namir Jul 08 '13 at 16:46
  • The ExpandoObject used with `dynamic` looks pretty much like the VB.NET "!" syntax for properties with a string-type indexer, aside from using "." rather than "!" (in vb.net, `Foo!Biz!Baz.St` is equivalent to `Foo["Biz"]["Baz"].St); for some applications I took to using the VB style back before Expando-Object existed (I use a dot rather than `!` on the last layer to allow it to be strongly typed). What differences do you see between dynamic+Expando-Object and the VB style "!"? – supercat Aug 21 '13 at 20:05
  • 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 '13 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 '14 at 12:07
  • 1
    @SeanMill yes you're right about it. I just mean that "the given example" by the answerer can be better done using anonymous types. That is if all the properties are statically known. If you want to add properties dynamically, then you've to go the dictionary route again. – nawfal Nov 11 '14 at 13:24
  • 1
    Why not do a `Dictionary` instead of `ExpandoObject` for the root object, so the code for nested properties becomes just as easy: `Console.WriteLine(dict["Address"]["State"]);` ? – NetMage Jan 12 '18 at 20:30
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.

itowlson
  • 73,686
  • 17
  • 161
  • 157
  • 8
    It [seems that databinding to dynamic objects is broken](https://connect.microsoft.com/VisualStudio/feedback/details/522119/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 05 '13 at 21:04
  • 2
    For those curious, I am currently able to bind to `List` and `IEnumerable` using WPF4 – Graham Bass Dec 04 '15 at 08: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}" />
bjull
  • 571
  • 4
  • 4
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.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Drew Marsh
  • 33,111
  • 3
  • 82
  • 100
21

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

ChaosPandion
  • 77,506
  • 18
  • 119
  • 157
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.

gn22
  • 2,076
  • 12
  • 15
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.

Auzi
  • 337
  • 3
  • 13
sgnsajgon
  • 664
  • 2
  • 13
  • 56
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).

bluish
  • 26,356
  • 27
  • 122
  • 180
n1LWeb
  • 41
  • 2
-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...
alan2here
  • 3,223
  • 6
  • 37
  • 62
-3

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

Eng. M.Hamdy
  • 306
  • 1
  • 3
  • 12
  • 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 08 '18 at 00: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. – Eng. M.Hamdy Feb 09 '18 at 02: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 09 '18 at 08: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 09 '18 at 08:16