a blog for those who code

Sunday 10 January 2016

The dynamic Primitive Type in C#

In this post we are going to discuss about dynamic Primitive Type in C#. As you all know C# is a type-safe programming language which actually means that C# checks all its types has correct value at compile time rather than at run-time.

The importance of type-safe programming language is that your errors are detected at compile time, thus helping the developers to save a lot of time. Now sometimes there are instances where you are not sure what will be the type of the result until run-time.  Thus dynamic Primitive Type came to your rescue.

The dynamic type helps you to bypass the compile time type checking. It drops the compile time safety check and  allows you to compile the code that relies on type that are only available at run-time. C# Compiler generates a special IL code (or payload) that describes the desired operation if you invoke your member by using a dynamic variable. Now this payload will execute the operation based on the actual type of the object at run-time.

Sample Code :

public static void Main() {
  dynamic result = 1;

  result = "Hello World Dynamic";

The above code will give output as :

Hello World Dynamic

In the above code since result type is dynamic, C# Compiler omits the compile time checking of result variable. It is also possible to use dynamic when specifying generic type arguments to a generic class, a structure, an interface, a delegate or a method. When you do this compiler converts dynamic to object.

Usage of dynamic

Try not to use dynamic in all cases where it can be used because then there will no meaning of type-safe or compile time checking. It will also slow down your application. This can be used to when c# communicates with other dynmic languages like python o ruby.

Difference between dynamic and var

Do not confuse between dynamic and var. var is a statically typed variable, which means data type of these variables are inferred at compile time where as dynamic variable's data type are inferred at run time. The var keyword can be used for local variables whereas the dynamic keyword can be used for local variables, fields and arguments. You need to explicitly initialize a variable declared using var, whereas you do not have to initialize a variable declared with dynamic.

Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment