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.

1 comment:

  1. Harrah's Cherokee Casino & Hotel - Mapyro
    Harrah's Cherokee Casino & Hotel is Cherokee, 김천 출장마사지 North 경상북도 출장안마 Carolina's closest casino to 안산 출장마사지 Great Smoky Mountains National Park. The casino's 40000 square 서산 출장안마 foot 제주도 출장샵 gaming

    ReplyDelete