Click here to Skip to main content
Click here to Skip to main content

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; 
      Console.WriteLine(content);

      // 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;

      Console.WriteLine(retMessage);
}

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)
{
      Console.WriteLine(obj.Name);
      obj.Name = "Abhijit";

      Console.WriteLine(obj.GreetMe());
}

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);
});
p.ResolveDynamic(d);

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 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.

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);
            }
            else
                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))
            {
                this.Dictionary.Remove(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;
});

            Console.WriteLine(expandoObject.Name);
            Console.WriteLine(expandoObject.CallMe("Hello"));

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

expandoObject.Dictionary.Remove("Name");

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.

License

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

About the Author

Abhishek Sur
Architect
India India
Did you like his post?
 
Oh, lets go a bit further to know him better.
Visit his Website : www.abhisheksur.com 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.
http://bit.ly/EXPERTCookBook
 
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.
 
Presently he is working in WPF, a new foundation to UI development, but mostly he likes to work on architecture and business classes. ASP.NET is one of his strength as well.
Have any problem? Write to him in his Forum.
 
You can also mail him directly to abhi2434@yahoo.com
 
Want a Coder like him for your project?
Drop him a mail to contact@abhisheksur.com
 
Visit His Blog

Dotnet Tricks and Tips



Dont forget to vote or share your comments about his Writing
Follow on   Twitter   Google+

Comments and Discussions

 
QuestionTooling support for expando objects? PinmemberAbbas Malik14-Jul-10 21:59 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 5 Jul 2010
Article Copyright 2010 by Abhishek Sur
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid