Difference Between Dynamic & Var

Introduction

 
In this blog, we are discussing the difference between the Dynamic and Var keywords.
 
If I try to put the deference in one sentence, Var is bound early. In other words, it's statically checked. Dynamic is late binded, in other words, dynamically evaluated. 
 
Let's discuss this deference through a simple program.
 
In the below code, I have declared x as a var and assigned the string value. In the next statement, I am trying to grab a length of the string.  
  1. static void Main(string[] args)  
  2.         {  
  3.   
  4.             var x = "string value";  
  5.             int length = x.Length;  
  6.                
  7.         }  
So, the first thing we need to notice is when we type second line, x.length, we can see that it is intelligent, in other words the compiler knew the length property. If I move my mouse property or the compiler has figured out that X is a string data type, it means that var is early bound.
 
Please check out the below snapshot. 
 
Difference Between Dynamic And Var
 
Let's look at the dynamic example.
 
We can see in the below code snippet that we will not get any intelligence because dynamic is late binding. 
  1. dynamic y = "string value";  
  2. int length2 = y.Length;  
Then, the question is, How is the compiler calling the length method in run time? Y dynamically runs using the reflection method. It will find the appropriate method.
 
One more difference is when we are dealing with the dynamic keyword, we will not get any compile-time errors. For example, in the below code, if we compile, we will not get any errors but in run time we will encounter the exception.
  1. dynamic y = "string value";    
  2. int length2 = y.length;    
Please check the below snapshot.
 
Difference Between Dynamic And Var
 

Summary

 
In this blog, we have discussed the difference between dynamic and var with some simple programs.