Feature Post

Top

.NET 4.0: ExpandoObject

Couple of articles ago, I did write about new dynamic type feature in C# 4.0

Some what related to the dynamic is the ExpandoObject.

Yep I know it does sound like an eight armed sea creature, but don't worry - its just an object that comes with .NET 4.0. Dont know what Microsofties think whenever they come up with such a name.

MSDN says, ExpandoObject "represents an object whose members can be dynamically added and removed at run time."

Add a property:
sampleObject.test = "Dynamic Property";
Console.WriteLine(sampleObject.test);
Console.WriteLine(sampleObject.test.GetType());

Output:
// This code example produces the following output:
// Dynamic Property
// System.String


Remove a property:

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
((IDictionary)employee).Remove("Name");

Associate and call events dynamically:

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

        // Create a new event and initialize it with null.
        sampleObject.sampleEvent = null;

        // Add an event handler.
        sampleObject.sampleEvent += new EventHandler(SampleHandler);

        // Raise an event for testing purposes.
        sampleObject.sampleEvent(sampleObject, new EventArgs());
   }

    // Event handler.
    static void SampleHandler(object sender, EventArgs e)
    {
        Console.WriteLine("SampleHandler for {0} event", sender);
    }
}

Output:
// This code example produces the following output:
SampleHandler for System.Dynamic.ExpandoObject event.

Cons of ExpandoObject:

Though the usage of dynamic keyword seems quite interesting; but it could become very hard to catch errors. For instance, a new developer who doesn't know much about it adds a property that was not required; the compiler won't show an error - only, probably runtime will. This means, typos won't be picked up during compile time because you can just declare about anything anywhere.

Plus, this code gives an impression that it type-safe, which it clearly, is not.

Even the tools like ReSharper would not be able to grab that error.

Anyway, you may also want to look into the unusual uses of Expando Object.

Happy coding!