Dynamics in C#

 Dynamics in C#

The history of Dynamic


Programming languages can be categories as Static and Dynamic Languages.

In Static languages, resolving types, members, properties are done at the compile time. If they are not defined, then during compile time we get error. Examples of static languages are C++ and C#.

In Dynamic languages, resolving types, members, properties are done at the runtime. So, you don't get an error during compile time. If you have worked with JavaScript, you can understand this concept easily. In JavaScript, we have let keyword to define a variable and assign it to a string. I can reassign the same variable to an int in Dynamic-typed languages. 

Why Dyamics?


Now, coming to the point, Dynamic keyword was added in .Net to support interoperability with other languages such as COM and JavaScript. .Net introduced DLR on top of CLR to achieve this. 

What that means is that we don't know whether a COM reference object has a method and .Net cannot find it during compile time. Without Dynamic, we have to use reflections to find out if a method is available; if available, then invoke the method. Using Dynamic, we can do it more easily.

Consider below code:


{
    object obj = "bharath";

    obj.IsThisName();
}


The second line in the boave code throws an error sayign that IsThisName() method is not available.


{
    dyanamic obj = "bharath";

    obj.IsThisName();
}

Using dynamic, the error is resolved, but you can see the error during runtime.

Difference between Var and Dynamics


Var is used to making coding easier. When we use var, we don't worry about the data type and the compiler resolves it for us. Hence, compiler finds the data type for us.

But Dynamic are used for different purpose altogether as discussed above.