| Var | Dynamic |
| 1. The var keyword was introduced in .net 3.0 framework | The Dynamic keyword was introduced in .net 4.0 framework |
| 2. var is used to declare a variable, its data type is determined at the time of its declaration that means it is decided at compile time. | Dynamic is also used to declare a variable, however its data type is not determined at the time of its declaration that means it is decided at run time. |
| 3. You cannot change its type at run time. | You can change its type at run time. |
| 4. For e.g. if you declare a variable and assign a value(i.e. var variable1 = 1;)in that case compiler will considered it as integer and at run time if u change its value to string, an error will be thrown conversion from string to integer is failed. | For e.g. if you declare a variable and assign a value (i.e. Dynamic variable1 = 1;) in that case compiler will not determine its type and run time you can change its value from string to integer. |
| 5. The advantage of var : if u assign any value from any objects or variables to var, you will not have to decide its type explicitly, the compiler will set its data type based on assigned value and hence it useful for linq | The advantage dynamic : since value can be assigned at run time you can changes its data type by assigning value of type objects or variables at run time. |
| 6. One more thing about var to remember is, var cannot be declared at class level and also it cannot be used as return type for any function. | However dynamic can be declared at class level and also it can be used as return type for any function. |
|
7. Any invalid
operation is caught at compile time. E.g. public class ClsStudent In above mentioned example compiler will throw an error since it will not get function FunPubStd2 while compilation. |
Any invalid operation is caught at run time E.g. public class ClsStudent In above mentioned example compiler will not throw an error since it will not check at run time. |
Join the conversation! Your thoughts help the community grow.
Sign in to leave a comment
It is the same account you read, post and publish with — and you will come straight back to this page.
Anil KumarPosted Apr 22, 2013, 10:27 AM
Please correct your example of dynamic. you have put var instead dynamic keyword.