Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Since I wrote the MSDN article you are referring to, I guess I have to answer this one.</p> <p>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: <a href="http://blogs.msdn.com/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the-expandoobject.aspx" rel="noreferrer">Dynamic in C# 4.0: Introducing the ExpandoObject</a>. </p> <p>Shortly, ExpandoObject can help you create complex hierarchical objects. For example, imagine that you have a dictionary within a dictionary:</p> <pre><code>Dictionary&lt;String, object&gt; dict = new Dictionary&lt;string, object&gt;(); Dictionary&lt;String, object&gt; address = new Dictionary&lt;string,object&gt;(); dict["Address"] = address; address["State"] = "WA"; Console.WriteLine(((Dictionary&lt;string,object&gt;)dict["Address"])["State"]); </code></pre> <p>The deeper is the hierarchy, the uglier is the code. With ExpandoObject it stays elegant and readable.</p> <pre><code>dynamic expando = new ExpandoObject(); expando.Address = new ExpandoObject(); expando.Address.State = "WA"; Console.WriteLine(expando.Address.State); </code></pre> <p>Second, as it was already pointed out, ExpandoObject implements INotifyPropertyChanged interface which gives you more control over properties than a dictionary.</p> <p>Finally, you can add events to ExpandoObject like here:</p> <pre><code>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; if (e != null) { e(d, new EventArgs()); } // We could also fire it with... // d.MyEvent(d, new EventArgs()); // ...if we knew for sure that the event is non-null. } 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); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload