Dynamic data type
Dynamic is a new data type introduced in C# 4.0 (.Net 4.5). This is used to avoid compile time type checking. The type will be resolved at run time for dynamic type variables.
Dynamic type will be declared using dynamic data type.
The dynamic type changes its type at the run time based on the value present on the right-hand side.
Example:
- dynamic VariableName = 100;
- dynamic name;
Var vs dynamic
Var type also accepts any type of data but for var type variable the type will be resolved during compile time.
With the Dynamic type variable the type will be resolved during run time. During declaration there is no need to assign any default value for dynamic type variables.
During declaration we need to assign default value for var type variables.
var data type can not be used in function return type.
Dynamic data type can be used in function return type.
T vs dynamic
For T type variable the type will be resolved during compile time.
For dynamic type variable the type will be resolved during run time.
dynamic variable
For this type of variable any type of value can be assigned without using any type casting. This type of data type is more useful where we handle different types of data types.
- dynamic Name = "flower";
- dynamic Age = 2;
- dynamic value = 3.500;
-
- System.Console.WriteLine($"Name:{Name}" );
- System.Console.WriteLine($"Age:{Age}");
- System.Console.WriteLine($"Value:{value}");
Dynamic function parameter
Function parameter can be defined as dynamic type:
- class Program {
- static void Main(string[] args) {
- dynamic i = Add(10, 30);
- dynamic f = Add(10, 30.5);
- dynamic c = Add(10.5, 30.5);
- }
- static dynamic Add(dynamic a, dynamic b) {
- return a + b;
- }
- }
Dynamic class object
Class object cannot be declared as dynamic type. This is because class object types are resolved during compile time.
- dynamic obj = new Student();
- obj.GetData();
Conclusion
Dynamic data type is more useful where we handle different types of data types.
This type will be useful in a method where we can return different types of data types without doing any type conversion.