Here describe the difference between Var, Object, and Dynamic keywords in c sharp.
Var
Var keyword is introduced in C sharp version 3.0. Var is used in method scope (used inside the methods) to implicitly (not directly expressed) type variable. The compiler decides which type it is at runtime. Can able to see the type of the variable by hovering over the var keyword.
ex,
- Var test = "name" or Var test = 3;
Object
Any type of data can able to assign to the object. The compiler decides which type it is in runtime but if you want to use type, firstly we need to cast explicitly (manually).
ex,
- Object test = "name" or Object test = 4;
casting object to string,
- string a = (string) test; or int a = (int)test;
Dynamic
The dynamic keyword is introduced in C sharp version 4.0. The dynamic keyword is similar to the Object keyword, we can assign anything to a dynamic variable. The compiler decides which type it is in runtime. The main difference between an object and dynamic keywords is explicit (manual) cast not required if you want to use type.
ex,
- Dynamic test = "name" or Dynamic test = 3;
- string a = test; or int a = test;
Here casting is not done while converting from dynamic to string or int data type.