Pages

Monday, July 5, 2010

Dynamic Behaviour on Objects at Runtime With Custom ExpandoObject

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

Being C# 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 a developer 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 be 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 time being.

Difference Between Object and Dynamic

When I first came across with dynamic in C# 4.0, I have wonder why do we require this. We have object which can hold any objects into it as it is called as 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 for dynamic. To demonstrate the situation let us take the example on how you can call properties or methods of an object for which you don't know the exact type.
Let I 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 returns 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 looks complex to you? Yes, it is. Probably if you have more flexibility like Static Method, or multiple argument 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... Its the beginning of 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 to 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 true sense.

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

Create Object that Extend 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 do 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.

Download Sample Application


For further Reference :
http://tomlev2.wordpress.com/2009/10/08/c-4-0-implementing-a-custom-dynamic-object/
http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx
http://blogs.msdn.com/b/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the-expandoobject.aspx

I hope you like this article. Please put your comment. Thanks for reading.

3 comments:

  1. You don't even need to to add the TryInvokeMember method, it will see the GreetMe as a property with type Action and then call it

    It works the same for non-dynamic stuff:

    class Test
    {
    Action TestMethod { get; set; }
    }

    var t = new Test { TestMethod = () => Console.WriteLine("Test" };
    t.TestMethod();

    ReplyDelete
  2. Yes. Its true.
    Actually if you dont override TryInvokeMember, when it is called, the base method will set result to null and return false.
    It then calls TryGetMember to get it from Dictionary and eventually calls the Action. You are right in this respect.
    On the other hand if you return true in TryInvokeMember, that means it has already invoked the member, and it will not call TryGetMember anymore. It is strange. I actually thought the reverse.

    So eventually our code doesn't require del.DynamicInvoke(args); to run.

    Good find buddy. I will seriously look more into it.

    ReplyDelete
  3. Mr. Expert,

    Are you going to have a follow up post or article about this anytime soon? :)


    _______
    "Providing you with great tips on Bankrupcty" ...
    ( http://www.QSLaw.com )

    ReplyDelete

Please make sure that the question you ask is somehow related to the post you choose. Otherwise you post your general question in Forum section.