ma.citi

A Coder's Blog

The ExpandoObject Class

The class ExpandoObject from System.Dynamics represents an object whose members can be dynamically added and removed at run time. The ExpandoObject supports runtime binding and implements the DLR interface IDynamicMetaObjectProvider, allowing you to share the expandoobject written in c# with another language that supports DLR interop.

The structure of ExpandoObject is a Dictionary of type string, object…as you can see in the reference source ExpandoObject class.

I created a simple object with some attributes and methods:

            
dynamic person = new ExpandoObject();

person.Name = "John";
person.Surname = "Lastname";
person.DateOfBirth = new DateTime(1960, 12, 12);
person.Mood = "happy";

person.PresentYourself = new Action(() => Console.WriteLine($"Hello! My name is {person.Name}"));
person.ChangeMood = new Action<string>(x => person.Mood = x);

Being a IDictionary<string, object> type, it allows me to print all the properties in the same way I’d do for a dictionary

foreach (var property in person)
{
    Console.WriteLine(property.Key + ": " + property.Value);
}

output:

Name: John

Surname: Lastname

DateOfBirth: 12/12/1960 00:00:00

Mood: happy

PresentYourself: System.Action

ChangeMood: System.Action`1[System.String]

Thanks to dynamic binding I’m able to access the properties of my ExpandoObject in a simple way e.g. person.Mood…without the need of using GetProperty() GetAttribute() etc

person.ChangeMood("sad");

Console.WriteLine(person.Mood);

person.PresentYourself();

output:

sad

Hello! My name is John