dynamic - dynamically typed.
Example 1:
dynamic di; //this code is valid.
di = "MKS"; //this code is valid.
di = 10; //this code is valid. Compiler will dynamically assign the type.
Example 2:
dynamic di; //this code is valid.
di = "MKS"; //this code is valid.
di++; //During runtime, this will throw an exception. Until this step and until running the code, compiler will not know that di is a string.
Use of dynamic is mostly helpful during the com components usage in C#. Mainly, when you are accessing the Excel (or any Office) objects using VSTO, you can use this flexibly with Excel objects avoiding type casting.
var - implicit but statically typed.
Example 1:
var d; //this is wrong. You should be giving some values to hint the compiler that d is of this type.
Example 2:
var d1 = 10; //this is valid.
d1 = "MKS";//This is invalid and it will fail during compile time itself. Because d1 is fixed to be an integer during the initial assignation. The message will be, 'cannot implicitly convert type string to int'.
Reference:
http://stackoverflow.com/questions/961581/whats-the-difference-between-dynamicc-4-and-var
Example 1:
dynamic di; //this code is valid.
di = "MKS"; //this code is valid.
di = 10; //this code is valid. Compiler will dynamically assign the type.
Example 2:
dynamic di; //this code is valid.
di = "MKS"; //this code is valid.
di++; //During runtime, this will throw an exception. Until this step and until running the code, compiler will not know that di is a string.
Use of dynamic is mostly helpful during the com components usage in C#. Mainly, when you are accessing the Excel (or any Office) objects using VSTO, you can use this flexibly with Excel objects avoiding type casting.
var - implicit but statically typed.
Example 1:
var d; //this is wrong. You should be giving some values to hint the compiler that d is of this type.
Example 2:
var d1 = 10; //this is valid.
d1 = "MKS";//This is invalid and it will fail during compile time itself. Because d1 is fixed to be an integer during the initial assignation. The message will be, 'cannot implicitly convert type string to int'.
Reference:
http://stackoverflow.com/questions/961581/whats-the-difference-between-dynamicc-4-and-var
No comments:
Post a Comment