You might have been asked the difference between var and dynamic variable in an interview.
Thus, I am listing the differences given below.
- The basic difference between var and dynamic variable is that if we declare a variable with var keyword, then its type checking is done at the time of compilation due to which if you writeYou need to specify the type at the time of the declaration
- var i; //You will get compile time error
Dynamic is checked at the time of runtime, due to which, even if you don’t assign any value at the time of the declaration, you won’t get any compiler error.- var dummy = string.Empty;
- dynamic test; // No Error
- We can pass dynamic type as a part of method parameterdeclaring.
- public void IsValidInput(dynamic input) //Correct
- Public void IsValidInput(var input) //Error
- If you need to write a generic method, you can make use of dynamic type to defer the type check until run time
- Public string GenericAdd(dynamic input) {
- input.Message = ”Generic Add Method”; //No error as your parameter type is dynamic
- return input.Message;
- }
- Suppose I have two different classes having Message properties
- Public class Test1 {
- Public string Message {
- get;
- set;
- }
- Public int counter {
- get;
- set;
- }
- }
- Public class Test2 {
- Public string Message {
- get;
- set;
- }
- }
- //Call GenericAdd method
- Console.WriteLine(GenericAdd(new Test1()));
- Console.WriteLineGenericAdd(new Test2());
I believe the above explanation will help you.

Alex LiPosted Feb 3, 2017, 7:53 PM
Good share,I can learn more detail from you article.
NehaPosted Jan 5, 2017, 5:38 AM
Nice one.............................................