Variable, Object and Dynamic data type in c#
The data types (var, object and dynamic) are generally used while you are working
with anonymous type.
Variable: This is a data type, var data type introduced since .Net Framework 3.0. Var datatype is pre-determined at compilation time. We cannot leave it unassigned or having a null value we need to implicitly assign a value to it otherwise we`ll receive an error. Var does not require explicit type casting for any operation at run-time and we cannot change the type of these variables at run-time.
Object: This is a root data type, object data type introduced since .Net Framework 2.0. Object data type is determined at run time. This is a alias for System.Object and object is the root of all classes (root data type).
In this we need to do boxing and unboxing to retrieve the actual value. The Object does not allow you to perform any operation such as mathematical operation without doing"boxing and unboxing". Its means we require explicit type casting for any operation at run-time. Useful when doesn't have more information about the data type.
Dynamic: This is a data type, dynamic data type introduced since .Net Framework 4.0. The dynamic data type allows you to perform any operations and will be resolved at run time. It does not require explicit type casting for any operation at run-time, because it identifies the types at run-time only. Dynamic type can be passed as
function argument and function also can return object type. Useful when coding using reflection or dynamic language support or with the COM objects, because we require to write less amount of code.
Example Code
- namespace EDUDOTNET_Var_Object_Dynamic
- {
- class Program
- {
- static void Main(string[] args)
- {
-
-
-
-
- var varItem = 100;
-
- varItem = varItem + 100;
-
-
-
-
-
-
- object objItem = 100;
-
- objItem = (int)objItem + 100;
-
-
-
- objItem = "EDUDOTNET";
-
-
-
-
-
- dynamic dynItem = 100;
-
- dynItem = dynItem + 100;
-
- dynItem += 100;
- dynItem = "EDUDOTNET";
- }
- }
- }