Saturday, 6 July 2013

Difference between Var and Dynamic keyword

In this article i am going to Discuss about difference between var and dynamic keyword

Var Keyword 

1.     It is introduced in C# 3.0 version
2.     The variable type is decided at compile time itself by compiler. when we mouse over the variable it will tell the data type.
3.     Variable should initialize at the declaration itself.
               var number 10 is correct.   
               var number;     not correct error ; 
           Implicitly-typed local variables must be initialized (CS0818) 
      4.  var can't be used as type in method parameter
5.     This  is statically typed.
6.     Errors caught at compile time.
7.     We can’t reassign the value of variable to another data type, because compiler already knows what kind of data type is declared.
  var  obj=1; 
  var  obj=”name”;   Error because already it defined as int type by compiler. 

Dynamic Keyword

      1.      It is introduced in C# 4.0
      2.      This is dynamically typed. Decides the type of variable at runtime by compiler.
      3.      No needs of initialize at declare time.
e.g., dynamic str; 
§  str =”I am a string”;  //Works fine and compiles
§  str=2;                  //Works fine and compiles
       4.      Error caught at runtime.
       5.      No intellisense.
       6.   dynamic should be used as a type in method parameter
               public void dyn(dynamic dd)
            dynamic add;

1 comment:

  1. This comment has been removed by a blog administrator.