Leveraging Dynamic CSharp in Application

Dheeraj Kumar Gunti

Reading Time : ( words)

From VS2010, we got to see a new type in the framework called dynamic. This is a static type. When ever we assign any value to the object of type dynamic, at compile time it identifies the type of value that got assigned to the object and it works accordingly.

If the assignment is wrong, we don't incur any kind of errors at compile time, we experience them at run time when working with dynamic type.

here in this tutorial in which we will see working with dynamic type in some of the cases. We can leverage dynamic type in lot of cases but in this tutorial we are covering three examples.

Lets say we have a StringBuilder class which performs string operations. In the below piece of code we see we are trying to use Reflection to identify specific method and invoking that. Where as if we use dynamic type its very simple and can be written with simple code.

Here we are trying to invoke a member AppendLine and we are invoking it as a method with some arguments which obviously is a string parameter which is to be appended.

When working with dynamic type, we specify the method straightforwardly which returns the result with cleaner code.

When we are working on any office applications like, excel or word etc. Its very complicated to derive them in to the application as we need to deal with Interop assemblies and its quite mess in the code too..

Using dynamic type we can achieve this with out having any Interop assemblies. In the below sample we see we are getting a excel type object and mapping that to a dynamic type and performing excel operations on that.

We are using Activator.CreateInstance which in turn creates an object of specific type. In this case its an Excel.Application.

We are performing all the excel related operations on the dynamic type object. The only care that we need to take case sensitiveness. Which results in runtime errors.

When we are dealing with json data and when we consume them in our application, its needed that we need to have a concrete class of that type when we deserialize them which can hold the data.

When working with dynamic type there is no need of going with a strongly typed deserialization and we can achieve the same results with out having a seperate class which can hold the data.

In the below example, we are having a json string and we are using dynamic type of customer and storing the json data as an object and manipulating the properties under it.

We can leverage dynamic type in lot of places. We have lot of dynamic classes, dynamic methods which are very helpful in the application.