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 write
You need to specify the type at the time of the declaration
- var dummy = string.Empty;
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.
- We can pass dynamic type as a part of method parameterdeclaring.
- public void IsValidInput(dynamic input)
- Public void IsValidInput(var input)
- 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”;
- 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;
- }
- }
-
- Console.WriteLine(GenericAdd(new Test1()));
- Console.WriteLineGenericAdd(new Test2());
I believe the above explanation will help you.