Home » Code | ASP.NET | Headline

Dynamic objects in C# 4.0

16. November 2009 by thebeebs 0 Comments

expando Ladies and Gentlemen allow me to introduce you to the fantastic Expando... I felt like I had to open this blog post like that because the name Expando conjures up the image of a cheap magician, a sort of dishevelled David Blaine. The similarities between this object and David Blaine do not end there; the dynamic way that this object can get and set properties really is magic. Ok it's no "Cutting a lady in half" or my imprisoned uncles "Hide the sausage" but it's special none the less.


Below you can see the new Expando object lets you add properties to an object on the fly at runtime...


dynamic contact = new ExpandoObject();
contact.Name = "Jeff";
contact.Age = 18;
contact.ContactInformation =  new ExpandoObject();
contact.ContactInformation.MobileNumber = "06078900567";
contact.ContactInformation.MobileNumber = "test@thewayithink.co.uk";
contact.Address = new List<dynamic>();
dynamic addy = new ExpandoObject();
addy.HouseNumber = 12;
addy.Postcode = "NN36QJ";

As you can see to add an object to an object you just set the property to be a new ExpandoObject. To create a list you simply add a new List<dynamic>() to one of the properties.


Dynamic Languages are fun, but I'm sure this will open up the floodgates to some awfully hacky code in the future.


Add comment

(Will show your Gravatar icon)  

  Country flag

  • Comment
  • Preview