Over a million developers have joined DZone.

Dynamic typing in C# 4.0

DZone 's Guide to

Dynamic typing in C# 4.0

· ·
Free Resource

The new release of the C# programming language introduces a new type – dynamic. Basically, now the developer can use the dynamic keyword to declare a variable (without explicitly specifying the type) and then perform various operations with it.

Here is an example:

dynamic unitA;
unitA = 1;
unitA = “Sample”;

Once the program is compiled, with this code included, no errors will be shown. The statements are correct and the variable inherits the data type of the assigned value. This can be confused with the object type, however, to demonstrate the differences, run this code:

dynamic unitA = “Sample”;
object unitB = “Sample”;
unitA += 1;
unitB += 1;


At first sight, it seems like both of the increment statement will result in an error. However, this only applies to the increment for the object. The incrementing process for the unitA won’t throw a compile-time error, while the incrementing operation for unitB will. This is one distinct difference between dynamic and object – the compiler won’t check that state of dynamic values (no compile-time type checking). However, an exception will be thrown at runtime if the type is incorrectly used.

Being dynamic, the instance can be exposed to the methods specific to it. For example, here I have a dynamic variable that contains a string. I want to get the substring from it, so I am using the standard Substring method to get it:

dynamic d = “Sample”;
string sub = d.Substring (0,2);
Debug.Print (sub);


It will work, since the assigned value is of string type that supports the Substring method. Also, notice the fact that after you insert the period, there are no IntelliSense suggestion. This is a way the IDE shows that it has no idea about the contents of the instance and it has no idea what can be done with it, so the developer has to make sure he/she uses the correct syntax and possible methods.

Try writing a completely random method call for d. For example, I am going to call SendToPrinter() that is in no way connected to the string type.

dynamic d = “Sample”;

At compile time, I will not get any errors. However, if I trigger the event handler, an exception will be actually thrown due to the usage of an unknown method.

As you see, the program identifies the string and then tries to call the method from the string-specific set. That not being found, will cause an error.

As an overall conclusion, I can say that dynamic typing is a really neat feature when it comes to interoperability and .NET usage with other dynamic languages (like Python or Ruby). However, the dynamic type also carries a lot of potential danger, keeping the developer responsible for the correct syntax of the calls and their type conversion and usage.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}