Friday, June 17, 2016

Difference Between var and dynamic

1. Var is introduced in 3.0 while dynamic introduced in 4.0.
2. Var is statically typed means type is decided at compile time. Dynamic is dynamically typed means type is decided at runtime.
3. Error caught at compile time in case of var while with dynamic error caught at runtime.
4.Need to initialize at compile time when you are using var. In case of dynamic no need to initialize at compile time.
var obj;
var obj1=null;
Above statement give compile error. While below statement will not give any error.
dynamic obj;
dynamic obj1=null;
5. Intellisense work for var but not for dynamic.
6. Below statement will not compile
var obj =12;
obj = "Hello"
While these statements perfectly fine with dynamic.
dynamic obj =12;
obj = "Hello"
7. var can not be passed as an arguments and function can't return var type. While dynamic can be passed as an argument and function also can return dynamic.
7. var is type safe , dynamic is not.
8. var can't used as a property while dynamic can.
9.var can be use as a local variable only. Member var type not allowed. Dynamic can be use as a member variable as well as local.

No comments: