Click here to Skip to main content
13,558,860 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


4 bookmarked
Posted 5 Jul 2010
Licenced CPOL

Dynamic Behaviour on Objects at Runtime With Custom ExpandoObject

, 5 Jul 2010
Rate this:
Please Sign up or sign in to vote.
The article describes how you can deal with dynamic object to inject members during runtime. It also demonstrates how to create Custom DynamicObject.

.NET 4.0 comes with lots of new features. One of the interesting things that it comes with is the Dynamic Behaviour of an object. If you have already read my article on C# 4.0, you know the basics of how to work with dynamic keyword in your application. In this post, I will introduce how you could use ExpandoObjects, a new way of writing your truly dynamic code and also take you deep into how you could create your own ExpandoObject.

C# being a strongly typed language, you might wonder how you could make it dynamic. In C#, everything that we define will have a strong signature. There are numerous languages available like Python, Ruby, and most notably JavaScript which are not strongly typed and you can change the object anytime whenever you require. C# 3.5 or below doesn't support changing the type dynamically during runtime. But as developers, we generally miss this flexibility of the language. But seriously, that shouldn't change the class of the language like what C# is. I mean, by adding up features like dynamic language, we shouldn't compromise with C# as a strongly typed language.

Microsoft introduced dynamic in C# with C# 4.0. But believe me, C# is not a truly a dynamic language now. Hopefully, they will introduce it in .NET 5.0. Let us talk about dynamic keyword a bit for the time being.

Difference Between Object and Dynamic

When I first came across dynamic in C# 4.0, I wondered why we required this. We have object which can hold any objects into it as it is called as the mother of all objects. Objects can hold anonymous types or even call properties or methods of an anonymous type easily, so what exactly do we require dynamic for. To demonstrate the situation, let us take the example of how you can call properties or methods of an object for which you don't know the exact type.
Let us have a class Person which looks like:

internal class Person
     public string Name { get; set; }
     public int Age { get; set; }
     public double Weight { get; set; }
     public string GreetMe()
         return string.Format("Hello {0}", this.Name);

Now let our method GetObject return an object of Person class as object. So to call properties or methods, we would write like:

public void ResolveStatic(object obj)
      PropertyInfo pinfo = obj.GetType().GetProperty("Name");

      //To Get from a property Name
      object value = pinfo.GetValue(obj, null);
      string content = value as string; 

      // To Set to Property Name
      pinfo.SetValue(obj, "Abhijit", null);

      //Invoke a method 
      MethodInfo minfo = obj.GetType().GetMethod("GreetMe");
      string retMessage = minfo.Invoke(obj, null) as string;


This is really what you expect to write. Does it look complex to you? Yes, it is. Probably if you have more flexibility like Static Method, or multiple arguments for a method, or even an indexer, your code will look horrendous.

dynamic keyword helps you in this regard. Yes, you can simply call methods and properties in your code without writing the whole Reflection methods, and the compiler will do them for us. So doing the same thing with dynamic, the code will look like:

public void ResolveDynamic(dynamic obj)
      obj.Name = "Abhijit";


So, the code looks the simplest and same as to known types. Actually if you see through the reflector, you will see that the same code is created by the compiler for us. So dynamic keyword makes our code look simple for dynamic types and also make the code easy to understand.

So, are you thinking this is the end of this? Nope... It's the beginning of the capabilities of dynamic. Let us discuss the true feature of dynamic in detail.

ExpandoObject, A True Dynamic Object

ExpandoObject is a new class added to enhance the dynamic capabilities of C# 4.0. ExpandoObject lets you add methods or members to an object dynamically during runtime. Let us discuss this in detail using an example:

Let us create our class Person dynamically in runtime using ExpandoObject. To do this, we just need to write:

dynamic d = new ExpandoObject();
d.Name = "Abhishek Sur";
d.Age = 26;
d.Weight = 62.5d;
d.GreetMe = new Action(delegate()
      Console.WriteLine("Hello {0}", d.Name);

So here you can see, the object ExpandoObject is extended in runtime to add properties and methods dynamically. Isn't it cool? Now the language is truly flexible and dynamic in a true sense.

If you are wondering how it is possible, or the depth behind creating the ExpandoObject class, let's read further to create your own Dynamic object.

Create Object that Extends in RunTime (Custom ExpandoObject)

To understand how a statically typed language can extend properties and class in runtime, or how this could be made possible, you need to delve deep into the internal structure of ExpandoObject.

Actually ExpandoObject is a Collection of KeyValuePair<string, /> </string, /><string, />where the Key represents the interface through which the objects are called for and the Value is the object which might be a string, an object or a method depending on what you pass. When we pass the methods, properties to an ExpandoObject it actually adds those as a KeyValuePair into its collection, and when the object is invoked, it calls up the method or property dynamically. </string, />

Now to create your own Custom ExpandoObject, you need to inherit your class from IDynamicMetaObjectProvider. This interface has a method called GetMetaObject, which you need to implement to create DynamicMetaObject from the Linq expression. On the first instant, it seemed to me as a trivia, but it is not. You actually need to parse the complex Linq Expression to create your Meta object. I must thank Microsoft for giving an implementation of IDynamicMetaObjectProvider as DynamicObject. So for simplicity, you can inherit your class from DynamicObject and get your job done.

Let us implement our class from DynamicObject:

public class CustomExpando : DynamicObject
        public IDictionary<string, object> Dictionary { get; set; }

        public CustomExpando()
            this.Dictionary = new Dictionary<string, object>();

        public int Count { get { return this.Dictionary.Keys.Count; } }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
            if (this.Dictionary.ContainsKey(binder.Name))
                result = this.Dictionary[binder.Name];
                return true;
            return base.TryGetMember(binder, out result); 	//means result = null 
							//and return = false

        public override bool TrySetMember(SetMemberBinder binder, object value)
            if (!this.Dictionary.ContainsKey(binder.Name))
                this.Dictionary.Add(binder.Name, value);
                this.Dictionary[binder.Name] = value;

            return true;

        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, 
		out object result)
            if (this.Dictionary.ContainsKey(binder.Name) && 
			this.Dictionary[binder.Name] is Delegate)
                Delegate del = this.Dictionary[binder.Name] as Delegate;
                result = del.DynamicInvoke(args);
                return true;
            return base.TryInvokeMember(binder, args, out result);

        public override bool TryDeleteMember(DeleteMemberBinder binder)
            if (this.Dictionary.ContainsKey(binder.Name))
                return true;

            return base.TryDeleteMember(binder);

        public override IEnumerable<string> GetDynamicMemberNames()
            foreach (string name in this.Dictionary.Keys)
                yield return name;

Here we have overridden methods:

  1. TryGetMember: Called when Get method of a Property is called. If returned true, the value in result will be returned.
  2. TrySetMember: Called when Set method of a property is called. If returned true, the value in result will be set to the member.
  3. TryInvokeMember: Called when a delegate/method is called. The result will be returned.

Unless others are required, you can use these members only to have an ExpandoObject. Quite easy, huh? Yes. To use this class, we use:

dynamic expandoObject = new CustomExpando();
expandoObject.Name = "Akash";
expandoObject.CallMe = new Func<string, string>(delegate(string name)
       expandoObject.Name = name;
      return expandoObject.Name;


Now to remove a member, you just need to use:


So this is it. Now you can handle your ExpandoObject yourself.

For further reference:

I hope you like this post. Please put your comments. Thanks for reading.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Abhishek Sur
India India
Did you like his post?

Oh, lets go a bit further to know him better.
Visit his Website : to know more about Abhishek.

Abhishek also authored a book on .NET 4.5 Features and recommends you to read it, you will learn a lot from it.

Basically he is from India, who loves to explore the .NET world. He loves to code and in his leisure you always find him talking about technical stuffs.

Working as a VP product of APPSeCONNECT, an integration platform of future, he does all sort of innovation around the product.

Have any problem? Write to him in his Forum.

You can also mail him directly to

Want a Coder like him for your project?
Drop him a mail to

Visit His Blog

Dotnet Tricks and Tips

Dont forget to vote or share your comments about his Writing

You may also be interested in...

Comments and Discussions

QuestionTooling support for expando objects? Pin
Abbas Malik14-Jul-10 21:59
memberAbbas Malik14-Jul-10 21:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.180515.1 | Last Updated 5 Jul 2010
Article Copyright 2010 by Abhishek Sur
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid