Difference Between Dynamic and Var Keyword in C#

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.
  1. dynamic d; //ok  
  2. var t = "Test"//ok  
  3. var k; //compile time error  
The ‘dynamic’ type is also helpful when you are interacting with COM APIs.
Ebook Download
View all
Learn
View all