Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Dynamic Behaviour on Objects at Runtime With Custom ExpandoObject

0.00/5 (No votes)
5 Jul 2010 1  
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:

C#
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:

C#
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:

C#
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:

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

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:

C#
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:

C#
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:

C#
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here