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; // Compile time error because implicit conversion is not possible
- obj = (int)(obj) + 1; //no error as we did the conversion.
- obj = "hello"; // No error as boxing happens here
- obj = (int)(obj); //no type checking is performed hence run time exception
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; // this assignment decides the type of variable "typevar" as integer type
- typevar = typevar+ 10; // No error
- typevar= "hello"; // Since, var does compile time type check and hence assigning a string value will result in error.
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; // No error
- testdynamic = "hello"; // No error, neither compile time nor run time
- 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,
This code results in a compile time error.- public void calculate(dynamic check) { }
- public void calculate(object check) { }
Join the conversation! Your thoughts help the community grow.