C# dynamic Data Type

Updated on September 20, 2015 Kisan Patel

The dynamic data type is a new data type that supports the late binding. This implies that all the member functions and member variables such as fields, methods and properties that are associated with dynamic keyword are ignored at compile time. The compiler preserves all the information about the expression, such as data type is similar to the var data type.

The difference between the var and dynamic data types is that var is strongly type checked at compile time; whereas, the dynamic data type is type checked by the compiler only at run time. After declaring a var data type, you cannot explicitly change its type throughout the execution of the program.

In the above code, the NonExistFunction() function is not declared or defined anywhere in the class, the str variable, which is of the var data type calls this method. The error generated by the compiler for the above code is shown in below screenshot:

The error generated by the compiler indicates that the var keyword recongnizes the value, operators, method assigned to it. Now, let’s compile the same code by replacing the var keyword with the dynamic keyword, as shown in the following code:

In the above code, the NonExistFunction() method called by the str variable, which is of the dynamic data type. In this case, the compiler does not check whether the method exists or not, as it is associated with the dynamic keyword. Therefore, the compiler does not raise any error and compiles the successfully. The dynamic data type is very useful when the programmers want to allocate tha data type of the variable at run time or to store the values generated by the program at runtime.

Note that the dynamic data type is data type that is resolved at runtime, instead of compile time.

Let’s take one example to understand how you can use dynamic data type in C#.