Dynamic type in C# is typically a data type , that was introduced in C#.Net 4.0 . As the name suggests its dynamic in nature which means the type information evaluates dynamically during run time.
So, basically when we declare a dynamic type variable, the compiler doesn’t make any type check during compilation time. It looks at the type of expression on the right side of the assignment operator (=) and determines actual type during run time.
Syntax & Usage of Dynamic type :
We can define dynamic type variables using dynamic keyword. In below example d is declared as dynamic, here compiler doesn’t know about the data type of d during compile time, it evaluates the type information during run time. In below case it will resolve type of d to System.String during run-time.
1 |
dynamic d = "hello"; |
Lets see some more example as below.
1 2 3 4 |
dynamic dn = "hello world"; Console.WriteLine(dy.GetType()); // Prints "System.String". dn = 100; Console.WriteLine(dy.GetType()); // Prints "System.Int32". |
In the above example dn is defined as a dynamic variable, Here the run-time derives the type in the first case dn to System.String type and the second case to System.Int32.
Example – 1 :
In below example.
- We have declared a dynamic variable and at run time we are assigning variables of different types to it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
using System; namespace DynamicType { class Program { static void Main(string[] args) { dynamic d = 12345; //Prints System.Int32 Console.WriteLine("Value : {0}, Data Type: {1}", d, d.GetType()); d = 12000d; //Prints System.Double Console.WriteLine("Value : {0}, Data Type: {1}", d, d.GetType()); d = 123.56m; //Prints System.Decimal Console.WriteLine("Value : {0}, Data Type: {1}", d, d.GetType()); d = true; //Prints System.Boolean Console.WriteLine("Value : {0}, Data Type: {1}", d, d.GetType()); d = "Test"; //Prints System.String Console.WriteLine("Value : {0}, Data Type: {1}", d, d.GetType()); d = DateTime.Now; //Prints System.DateTime Console.WriteLine("Value : {0}, Data Type: {1}", d, d.GetType()); Console.ReadLine(); } } } |
Output :
In above example the variable d is resolved to different data type at run time based on the assignment.
Lets look at below code example, here the code compiles successfully but throws an exception at run time.
1 2 3 |
dynamic d = "Hello World"; // The following line throws an exception at run time. d++; |
In the above example, Here compiler doesn’t know about the type information of variable d , hence it didn’t raise any error in line d++ during compilation. However during run time it throws an error, because compiler resolved the data type d to System.String type and increment operation d++ is not supported on a String type.
Usage of C# dynamic type in method and property :
If you assign a class object to the dynamic type, then the compiler will ignore all type check during compilation time. It won’t validate for correct methods and properties name of the dynamic type that holds the class reference.
Example – 2 :
If you look at below example,
- We have declared a class as Employee , it has a method as public int CalculateSalary(int type) and property as string Name
- In the Main method, we are creating an employee instance of type dynamic and accessing its method and property.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System; namespace DynamicType { class Program { static void Main(string[] args) { dynamic dynmEmployee = new Employee(); //Run time error since there is no Salary property - No Compilation error Console.WriteLine(dynmEmployee.Salary); //Run time error since there is no parameter - No Compilation error int Salary = dynmEmployee.CalculateSalary(); //Run time error invalid argument - No compilation error Salary = dynmEmployee.CalculateSalary("12345"); } } public class Employee { public string Name { get; set; } public int CalculateSalary(int type) { if (type == 1) return 20000; else return 30000; } } } |
In the above example, Employee class don’t have Salary property, hence compiler throws a run time error. Similarly compiler throws run time error while calling int Salary = dynmEmployee.CalculateSalary(); because of empty parameter and Salary = dynmEmployee.CalculateSalary("12345"); for invalid parameter. However in all cases there wont be any compile time error.
While using dynamic type it should be note that.
C# compiler does not check for the parameters count, type, non-existent parameter, property type, property existence etc during compilation. It validates all these information during run-time, and if it is not valid, then throws a run-time exception.
Dynamic type vs Object type :
All types in C#.Net are derived directly or indirectly from System.Object. We can assign values of any other types, value types, reference types, predefined or user-defined types to object type.
It does not allow to perform any mathematical operation without doing boxing and unboxing. Which means, we have to perform explicit type casting upon Object type for any run-time operation.
1 2 3 4 |
object obj ; //Reference type int x = 100; //Value type obj = x; //Boxing int y = (int)obj; //Unboxing |
Lets take below example.
1 2 |
object obj = 12345; int n = obj;//Compile error "Cannot implicitly convert type "object" to int. An explicit conversion exists |
Here in above, we have to cast the underlying type present in object before using it.
1 2 |
object obj = 12345; int n = (Int32)obj; |
In above, we cast the object type to System.Int32 type. However, using dynamic in this scenario doesn’t require any type cast, the compiler would fetch the exact type System.Int32 at run time.
1 2 |
dynamic d = 12345; int n = d;//No compilation or run time error |
Thanks for your time 🙂 feel free to provide your feedback and do check my other blogs on
Reference Type and Value type .