Adding properties and methods to an ExpandoObject, dynamically!

Posted by Filip Ekberg on October 2 2011 4 Comments

Meanwhile I am planning and writing manuscript and code samples for my upcoming video series that will cover “Programming fundamentals using C#”, I thought it was time for a short post on some dynamic programming in C#!

Another thing worth mentioning is that I will be using Visual Studio 11 Developer Preview, if you haven’t checked it out, I posted a quick blog post about it running side by side with Visual Studio 2010!.

So, for those that are completely new and haven’t yet checked out my videos on “C# 4.0 Using the Dynamic Keyword”, here’s a quick summary:

  • C# is not dynamically typed even though you can have dynamic types. It’s a statically typed dynamic type!
  • ExpandoObject is the object that you use with the dynamic keyword(contextual keyword) in order to add properties and methods dynamically.
  • Dynamics are evaluated at runtime

A typical dynamic setup that creates a dynamic object and adds a static amount of properties might look like this:

dynamic person = new ExpandoObject();
person.Name = "Filip";
person.Age = 24;

What is interesting about the ExpandoObject is that it implements the interface:

IDictionary<string, Object>

So what this means is that if we cast the person-object to an IDictionary we will be able to do some really cool stuff with it. The same code above but re-written to make use of the dictionary instead could look like this:

dynamic person = new ExpandoObject();
var dictionary = (IDictionary<string, object>)person;

dictionary.Add("Name", "Filip");
dictionary.Add("Age", 24);

Now you might ask why this would ever be useful? In fact I first encountered this when Rob Conery threw together a part of Massive on stage on the Norwegian Developers Conference this summer. In his case he wanted to create an extension for an IDataReader which would give you a List instead of having to fight with the IDataReader.

So to make this as dynamic as possible, all the fields from the table was read, added with their corresponding values from the IDataReader into the dictionary, which made the whole thing very dynamic.

There are actually more ORMs(Simple.Data) out there that uses this approach, but I will get to that later on when I’ll cover DynamicObject!

This is how you add dynamic properties, but how about adding a method? It’s simple!

What you do is that you add a new key to the dictionary and the object should just be an action, like this:

dictionary.Add("Shout", new Action(() => { Console.WriteLine("Hellooo!!!"); }));


When calling the Shout-method it will print out “Hellooo!!!” in the Console.

I hope you had fun reading this and that you learned something new! Stay tuned for more posts!

Vote on HN

4 Responses to Adding properties and methods to an ExpandoObject, dynamically!

  1. Per HejndorfNo Gravatar says:

    Good post, Filip. Exactly to the point of what I was looking for. Although “dynamic” is kind of scary, IDataReader is worse! I must get around to the Rob Conery video as well.

  2. Filip EkbergNo Gravatar says:

    Thank you Per!
    I agree with you on it being scary, I actually told Rob Conery on NDC that I thought talking about stuff like this can open a dangerous door. But the thing is that the tools are there, you can do scary stuff without using dynamic, so I say; Use dynamic when you think it is appropriet and when it makes sense for your application.

    Regarding the IDataReader, yes, that one is a bit more scary to work with! Here’s an extension-method that converts an IDataReader into a IList:

    public static class Extensions
        public static IList<dynamic> ToDynamic(this IDataReader reader)
            var result = new List<dynamic>();
            while (reader.Read())
                var item = new ExpandoObject();
                var dictionary = (IDictionary<string, object>)item;

                for (var i = 0; i < reader.FieldCount; i++)
                    dictionary.Add(reader.GetName(i), reader[i]);


            return result;

    I really like this approach, when it fits!

  3. JonNo Gravatar says:

    Interest post Filip. What practical uses does the ExpandoObject have?

  4. Filip EkbergNo Gravatar says:

    Hi Jon,

    According to MSDN this is what the ExpandoObject is:

    Represents an object whose members can be dynamically added and removed at run time.

    So in reallity it’s used whenever you need an object that you want to add properties to dynamically. For instance this would not be possible:

    dynamic person = new { Firstname = "Filip" };
    person.Surname = "Ekberg";

    Because person is really not a dynamic type that allows you to add properties to it, it’s an anonymous type in this case. But this would be valid:

    dynamic person = new ExpandoObject();
    person.Firstname = "Filip";
    person.Surname = "Ekberg";

    Does this answer your question?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>