C# 4.0 : Dynamic Behaviour on Objects at Runtime With Custom ExpandoObject

Abhi2434
Posted by in C# category on for Beginner level | Views : 15789 red flag
Rating: 4.33 out of 5  
 3 vote(s)

C# 4.0 adds a new feature called Dynamic. The inclusion of System.Dynamic creates special alternatives to create your own dynamic objects that behaves according to you during Runtime. The article demonstrates how you can use Microsoft's ExpandoObject and also lets you to deal with custom Dynamic Objects.


 Download source code for C# 4.0 : Dynamic Behaviour on Objects at Runtime With Custom ExpandoObject


Introduction



NET 4.0 comes with lots of new features. One of the interesting things that it comes with is the Dynamic Behavior 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.


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

Conclusion


I hope you like this post. Work with ExpandoObject in your code and take the full flavor of .NET 4.0.

Thanks for reading. Give your feedback.

Page copy protected against web site content infringement by Copyscape

About the Author

Abhi2434
Full Name: Abhishek Sur
Member Level: Silver
Member Status: Member,Microsoft_MVP,MVP
Member Since: 12/2/2009 4:19:08 AM
Country: India
www.abhisheksur.com
http://www.abhisheksur.com
Working for last 2 and 1/2 years in .NET environment with profound knowledge on basics of most of the topics on it.

Login to vote for this post.

Comments or Responses

Posted by: SheoNarayan on: 7/6/2010
Good work Abhishek, keep it up!

Login to post response

Comment using Facebook(Author doesn't get notification)