Friday, 18 July 2014

Difference between var and dynamic in c#.




var Vs dynamic



var
dynamic
1) It is a keyword that is used for implicit variable declaration 
ex: var a=100; 
var b="welcome"; 
 
The compiler determines the data type of the variable declared with var keyword 
on the basis of assigned value. we have to assign value with variable declaration 
ex: var a; 
a="welcome"; This is wrong 
It is a keyword used for variable declaration 

ex: dynamic a=100; 

dynamic b; 
b="good"; 

The data type of the variable is determined at runtime 
2) var cannot be used to declare variables at class level. 

dynamic can also be used to declare class level variables 

ex: class aa 
{ 
dynamic d; //correct 

} 
3) var cannot be used as the return type of methods. 

dynamic can also be used as return type of the methods 

example: 

class dd 
{ 
static dynamic pp() 
{ 
dyanmic d; 
d=<some value>; 
return d; 
} 
} 

4) Intoduced in c# 3.0 
Introduced in c# 4.0
5) Errors are caught at compile time.
Since the compiler knows about the type and the methods and properties of the type at the compile time itself
Errors are caught at runtime 
Since the compiler comes to about the type and the methods and properties of the type at the run time.
6) Visual Studio shows intellisense since the type of variable assigned is known to compiler.
Intellisense is not available since the type and its related methods and properties can be known at run time only


No comments:

Post a Comment