Sunday, August 16, 2015

Difference between Var and Dynamic type in c#

Var data type was introduced in .NET 3.5 with Visual Studio 2008 and Dynamic was introduce in .NET 4.0 with Visual Studio 2010.


Var Data Type:


Var declaration is resolved at compile time that means the type of variable declared is decided by the compiler at compile time.

Example: 

Var name = “Sachin is in India”; // Correct
Name =2; // Compilation error  

In this example, compiler set the name variable as string type at compile time. If you will assign another type value in “name” variable, it will give compilation error.

Please note that as var is compile time therefore you cannot leave it as blank. You have to assign some value at compile tome only.


Dynamic Data Type:

Dynamin declaration is resolved at Run time that means the type of variable declared is decided by the compiler at Run time.

Example: 

Dynamic name = “Sachin is in India”; // Correct
Name =2; // Correct

In this example, compiler set the name variable as string type at Run time. If you will assign another type value in “name” variable, it will not give you any error and change the type of variable at run time.

Please note that any error in dynamic variable will come only at run time because compiler does not understand the type of variable at compile time. It is not necessary that you will assign some value to Dynamic variable at compile time.

You can declare Dynamic data type like this:
Dynamic str;
Str=”Sachin”;
Str = 10;


Note: It is highly recommended that we should avoid using Dynamic as it does Boxing\UnBoxing and impact on application performance. We should use Dynamic only when it is really required.

No comments:

Post a Comment