Thursday, June 16, 2011

Difference between ‘dynamic’ and ‘var’ keyword


dynamic vs. var keyword

The major difference between ‘var’ and ‘dynamic’ keyword is when using ‘var’ keyword the type is known at compile time while using ‘dynamic’ keyword the type is known at runtime. ‘var’ keyword is strongly implicitly typed variable and compiler knows type of variable from the initialization. You can see the difference between both in below images.

On mouse hover over the ‘dynamic’ keyword







On mouse hover over the ‘var’ keyword








If you don’t initialize ‘dynamic’ type at the time of declaration then it is ok for compiler. But if you don’t initialize ‘var’ type at time of declaration you will get compile time error.

dynamic d; //ok
var t = "Test"; //ok
var k; //compile time error

The ‘dynamic’ type is also helpful when you are interacting with COM APIs.

No comments:

Post a Comment