The dynamic type was introduced in C# 4.0. It’s a new type like other data types such as int or double.The difference between dynamic type and other types is that dynamic type variable is not type checked by the compiler.So any value can be assigned to a dynamic type variable.
If we declare a variable of type dynamic as
dynamic strObj = "hello"; dynamic intObj = 1;
as you can see above values of type string and int are assigned to a dynamic variable.
But the main advantage of dynamic type is that the compiler will not check if the operations performed by a dynamic type variable are valid or not.So if we write the following statement our program will compile successfully.
strObj.NewMethod();
Even though the method NewMethod() is not defined by the string type still our code just compiles.Though at run time error will be thrown as NewMethod() doesn’t exist in the string type.
Use of dynamic type
If we are calling an API which is implemented in different language then by using the dynamic type we can easily call the API from our .NET code.
For example the data types used in java or python differs from the data types used in .NET.So if we are not using dynamic type then we need to cast the arguments to and from the object type to the actual .NET data type.By using the dynamic type in C# 4.0 we can avoid type type casting by using the dynamic type as API method arguments.
Some of the important points about dynamic type are:
- dynamic types should be used only when necessary.As dynamic type variable are not type checked by the compiler so it increases the chances of runtime exceptions in our application.
- It provides advantage over using objects for storing different types as type casting is not required.
- The dynamic language runtime or DLR is an API introduced in .NET Framework 4 which provides the ability to use dynamic type.
- The dynamic type in C# 4.0 can be assigned different types of values.For example the variable strObj is assigned the value “hello” and the reassigned the integer value 1.
dynamic strObj = "hello"; strObj = 1;
Leave a Reply