Home > .NET, C#, Dynamic > The Dynamic Duo: ExpandoObject and DynamicObject – Part 1

The Dynamic Duo: ExpandoObject and DynamicObject – Part 1

November 15, 2011 Leave a comment Go to comments

After shortly explaining the new dynamic keyword in my previous post we will look at the ExpandoObject class which offers a dynamic structure. What does this mean exactly?! Well you can get and set Properties which are not existent at design-time and also define and call methods on the ExpandoObject like this:

dynamic expando = new ExpandoObject()
expando.MyProperty1 = "This is a string prop";
expando.MyProperty2 = 12;
expando.MyFunction = (Func<String>)(() =>
                     {
                         return String.Format("{0}", expando.MyProperty1);
                     });

Furthermore it supports change notifications via INotifyPropertyChanged out of the box as well as Events (sort of).

So do you need this? As always: it depends. On what? Well if you are looking for a dynamic structure you could also use a combination of Dictionary-Voodoo like this:

Dictionary<String, object> paulie = new Dictionary<string, object>();
paulie["FirstName"] = "Paulie";
paulie["LastName"] = "Baker";

Dictionary<String, object> people = new Dictionary<string, object>();
people["Paulie"] = paulie;

Console.WriteLine(((Dictionary<string, object>)people["Paulie"])["FirstName"]);

Besides the much cleaner coding, there’s again INotifyPropertyChanged, Methods and Events on the Expando side. Also it implements IDynamicMetaObjectProvider which allows for interop with DLR objects.

As always the source can be downloaded here: http://dl.dropbox.com/u/13456770/IDevign/IDevign.Expando.zip

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.