Dynamic Data Type in C#

The dynamic keyword brings exciting new features to C# 4. Dynamic Type means that you can store any type of value in the dynamic data type variable because type checking for dynamic types of variables takes place at run-time. In order to use the dynamic type in C#, you use the dynamic keyword in place of another type name.

dynamic amDynamic = 100; dynamic dynStr = "Hello";

The key to the dynamic type is that the type checking is disabled until run-time. When you use the dynamic keyword you tell the compiler to turn off compile-time checking . So, it is not type safe i.e. Compiler doesn't have any information about the type of variable. This can produce problems if the run-time type does not support the members that are called.

dynamic var = "test"; Console.WriteLine(var++);// The following line throws an exception at run time.

The reason is that the compiler doesn't know the runtime type of the object and therefore can't tell you that the increment operation is not supported in this case. Absence of compile-time type checking leads to the absence of IntelliSense as well. Because the C# compiler doesn't know the type of the object, it can't enumerate its properties and methods. This problem might be solved with additional type inference , as is done in the IronPython tools for Visual Studio, but for now C# doesn't provide it.

Dynamic type as Parameter

Dynamic type can be passed as method argument so that it can accept any type of parameter at run time.

Example
using System; using System.Windows.Forms; namespace WindowsFormsApplication4 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { DisplayValue("Parameter Test !!"); //String DisplayValue(true); //Boolean DisplayValue(100); //Integer DisplayValue(100.50); //Double DisplayValue(DateTime.Now); //Date } static void DisplayValue(dynamic val) { Console.WriteLine(val); } } }

Casting is not required but you need to know the properties and methods related to stored type. It is effectively inherit the properties and methods appropriate to their type at runtime. The following code will run because str is a string at the point the Length property is used, for example:

dynamic str = "Hello"; Console.WriteLine(str.Length);

Limitations

In most situations it would be inadvisable to use the dynamic type unless you are integrating with a dynamic language or another framework where types are not known at compile time. Because the compiler does not know what type the dynamic variable will eventually become, so it’s unable to offer method or property code hints in Visual Studio.