Var Vs Object Vs Dynamic



Difference between Var, Object, and Dynamic keywords.

Var

Var keyword is used inside the method to implicitly type variable. At runtime, the compiler decides which type it is. We can able to see the type of the variable by hovering over the var keyword.

Var str = "name";
//or 
Var result = 30;

Object

We can assign any type of data to the object. At runtime, the compiler decides which type it is but if we want to use type, firstly we need to cast explicitly (manually).

Object str = "name";
//or 
Object result = 4;

casting object to string:

string a = (string) str;

casting object to integer:

int b = (int) result;

Dynamic

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 we want to use type.

Dynamic str = "name";
//or 
Dynamic result = 3;  

string a = str;
//or 
int b = result;

Here casting is not done while converting from dynamic to string or int data type.

 

0 Comment's

Comment Form

Submit Comment