views:

56

answers:

1

I am trying to learn all the new goodies that come with C# 4.0. I am failing to understand the differences between the Dynamic and Expando types. From the looks of things it seems like Dynamic is when you want to access variables etc from python scripts etc.Expando seems like a use ful tool when talking with COM/Office objects. I may be incorrect here and would really love to have some input on this.

Thanks in advance!!

+1  A: 

Expando is a dynamic type with the ability to add/remove members at runtime. dynamic is designed to allow .NET to interoperate with dynamic types when interfacing with dynamic typing languages such as Python and JavaScript. Expando is designed to handle dynamic data. So, if you need to handle a dynamic type: use dynamic. If you need to handle dynamic data such as XML or JSON: use ExpandoObject

The declaration of an expando shows the relationship between dynamic and the expando:

dynamic expando = new ExpandoObject();

And the ability to add a new property:

expando.SomeNewStringVal = "Hello Brave New Whirrled!";

...that line of code creates a brand new string property in the expando object called SomeNewStringVal. The string type is inferred from the assignment.

So an expando is a dynamic data type that can represent dynamically changing data. That's it in a nutshell. Here's a deeper look at dynamic and expando.

Complete example:

using System;
using System.Dynamic;

class Program
{
    static void Main(string[] args)
    {
        dynamic expando = new ExpandoObject();
        expando.SomeNewStringVal = "Hello Brave New Whirrled!";
        Console.WriteLine(expando.SomeNewStringVal);

        // more expando coolness/weirdness:
        var p = expando as IDictionary<String, object>;
        p["A"] = "New val 1";
        p["B"] = "New val 2";

        Console.WriteLine(expando.A);
        Console.WriteLine(expando.B);
    }
}
Paul Sasik