Friday, October 26, 2018

Difference between the 'var' and 'dynamic'

var           -    The type of the variable declared is decided at compile time
dynamic   -    The Type of the variable declared is decided at run-time. 
  • variable declared using var should be initialized at time of declaration. However variables declared using keyword dynamic don't have to initialize at time of declaration.
  • The type of variable value assigned to var is decided at compile time and cannot be assigned with other types in the code later, having though gives compile. However variables declared using dynamic, compiler will not check for the type errors at the time of compilation. So variable can be assigned with values of any type through the code consecutively.
  • variable declared using var gives the intelliSense. However the variable using dynamic doesn't show the intelliSense because the type is decided at run-time, compiler never knows its type during compilation time.
Code Snippet:

            var str = "Hello Developer.!"; // str is decided as type string at compile time.
            str = 1;
            // compiler error - Cannot implicitly convert type 'int' to 'string'
           

            dynamic dn = 1001;
            dn = "text"; 

            // NO error is thrown by compiler, though variable is assigned to string. compiler will create the type of dn as integer and then it recreates the type as string when the string is assigned to it.


Now,
dynamic dn;
dn = "text";
var vr = dn;

vr = 1001;

// vr is assigned with dynamic dn - So vr type is decided at run-time.