Wednesday, 18 September 2013

Creating dynamic object with Dynamic feature in CSharp

There were new features introduced in .Net 4.0 and one of the awesome feature was addition of System.Dynamic in framework library. With this dynamic objects C# can provide dynamic language features like Python.

A short brief of Dynamic objects is, Dynamic objects expose members such as properties and methods at run time, instead of in at compile time. This enables you to create objects to work with structures that do not match a static type or format. For example, you can use a dynamic object to reference the HTML Document Object Model (DOM), which can contain any combination of valid HTML markup elements and attributes.

People still gets confused with Dynamic vs Anonymous types. Just to clarify Anonymous types cause the compile time errors. While Dynamic types work upon run time late binding for object properties. Let’s take an example:

var anonymousObject = new { Name=”Anonymous”, Value=”Foo” } ;

if you use anonymouseObject.Index then It’ll throw an compile time exception because it only know the Name and Value as it’s property. But using Dynamic you can use object.UnknownProperty will not cause compile time error.Let suppose you have requirement to create a object with properties which could be in any no. and of any type you don’t know. So how will you do this operation? I’ll introduce you with an exciting type of class called ExpandoObject with in System.Dynamic.

dynamic runTimeObject = new ExpandoObject();
runTimeObject.Name = "OnTheFlyFooObject";
runTimeObject.Value = "FooIsMoo";

This will automatically append these properties to the object. Now if you ask for runTimeObject.OtherUnknownProperty then it’ll not give any error during compilation but this will be check when you run the program. So you can also check if the object have this kind of property before using any runtime property. Behind the scene it’s storing these property as a Dictionary. So you can cast the runTimeObject to IDictionary<string,object> to get the list of late bound properties on the object.

var propertyCollection = (IDictionary<String, Object>)runTimeObject;
if (propertyCollection.ContainsKey("OtherUnknownProperty"))

This is how you can be safe from getting any runtime exception. So you have seen how to use dynamic object with properties. Similarly you can also introduce run time methods to the dynamic object.

dynamic runTimeObject = new ExpandoObject();
runTimeObject.Name = "OnTheFlyFooObject";
runTimeObject.Value = "FooIsMoo";
runTimeObject.Print =
(Action)(() => { Console.Write("This a run time method for the dynamic on fly Foo"); });
//Now call the attached method

Isn’t is cool? Yes it is. But beware before using it in your ordinary scenario can cost you some CPU time. These are runtime late binding operations which requires its own time to resolve the symbols and so are less optimized than normal early binding cases.

So choose wisely with your scenario. In some cases this is really an awesome feature provided in recent version of CSharp. I would say that CSharp is not just a Object Oriented language but it’s adapting features of Functional, Dynamic language. That’s why it’ll will long last than any language in the programming world.

If you enjoyed reading this then please leave a comment or suggestions.