Creating Dynamic Object With Dynamic Feature in C#

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

A brief explanation of Dynamic objects is, Dynamic objects expose members such as properties and methods at run time, instead of 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), that can contain any combination of valid HTML markup elements and attributes.

People still get confused with Dynamic vs Anonymous types. Just to clarify, Anonymous types cause the compile time errors whereas Dynamic types work at run time by late binding of object properties. Let's use an example:

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

If you use anonymouseObject.Index then the It'll throw a compile time exception because it only knows the Name and Value as it's property. But using Dynamic, you can use object.UnknownProperty that will not cause a compile time error. Suppose you have a requirement to create an object with properties that could be in any number and of any type you don't know. So how will you do this operation? I'll introduce you to an exciting type of class called ExpandoObject within 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 a "runTimeObject.OtherUnknownProperty" then it'll not give any error during compilation but it will be checked when you run the program. So you can also check if the object has this property before using any runtime property. Behind the scenes it's storing these properties as a Dictionary. So you can cast the "runTimeObject" to a "IDictionary<string,object>" to get the list of late bound properties on the object.

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

This is how you can be safe from getting any runtime exceptions. So you have seen how to use dynamic objects 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
runTimeObject.Print();

Isn't it cool? Yes it is. But beware, before using it in your ordinary scenario it can cost you some CPU time. These are runtime late binding operations that require 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 the recent version of C#. I would say that C# is not just a Object Oriented language but it's adapting features of Functional and Dynamic languages. That's why it will last longer than any language in the programming world.

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


Similar Articles