C# Dynamic Data Type

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:
  1. dynamic VariableName = 100;  
  2. 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.
  1. dynamic Name = "flower";  
  2. dynamic Age = 2;  
  3. dynamic value = 3.500;  
  4.   
  5. System.Console.WriteLine($"Name:{Name}" );  
  6. System.Console.WriteLine($"Age:{Age}");  
  7. System.Console.WriteLine($"Value:{value}");  
Dynamic function parameter
 
Function parameter can be defined as dynamic type:
  1. class Program {  
  2.     static void Main(string[] args) {  
  3.         dynamic i = Add(10, 30);  
  4.         dynamic f = Add(10, 30.5);  
  5.         dynamic c = Add(10.5, 30.5);  
  6.     }  
  7.     static dynamic Add(dynamic a, dynamic b) {  
  8.         return a + b;  
  9.     }  
  10. }  
Dynamic class object
 
Class object cannot be declared as dynamic type. This is because class object types are resolved during compile time.
  1. dynamic obj = new Student();  
  2. obj.GetData();// during compile time no error will be thrown. but during run timer error will be thrown.  

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.