Object
C#, being object oriented, has everything derived from object type, be it directly or indirectly.
Some important points about "object" type:
- It is a compile time variable type
- It requires unboxing when you want get the actual type of the value assigned t it.
- The operation of unboxing makes it slow.
- It supports both boxing and unboxing.
- Run time exceptions may occur during unboxing.
Sample code for the same,
- objectobj = 1;
- obj = obj + 1;
- obj = (int)(obj) + 1;
- obj = "hello";
- obj = (int)(obj);
Var
Var is also a compile time variable type but the way in which it differs from object type is that it does not require boxing and unboxing.
Some important points about "var" type:
- All type checking is done at compile time only.
- Once Var has been initialized, you can't change type stored in it.
- No boxing/unboxing, hence it is memory efficient.
Sample code,
- vartypevar = 1;
- typevar = typevar+ 10;
- typevar= "hello";
Dynamic
Dynamic is a run time variable type.
Some important points about dynamic variable types:
- A value can be assigned to a dynamic type variable either at run time or compile time.
- The value assigned to a dynamic type can be changed at any time - run time or compile time.
- Only run time exceptions occur when we use dynamic type variable.
- "RuntimeBinderException" exception occurs when you try access a method that does not exist in dynamic type.
Sample code,
- dynamictestdynamic = 10;
- testdynamic = testdynamic + 10;
- testdynamic = "hello";
Other points
- Dynamic type and object type variables can be passed as arguments to methods.
- Dynamic type need not to be initialized during declaration while var type needs to be initialized.
- Since dynamic type and object type are more or less the same, we cannot write overloaded methods. An example of this is explained below,
- public void calculate(dynamic check) { }
- public void calculate(object check) { }
This code results in a compile time error.