How to Use Dynamic Types in C# 4.0

By Craig Buckler

Code purists will be horrified, but dynamic types have arrived in C# 4.0. In languages such as PHP and JavaScript, variables are loosely typed; there’s no need to declare what type of data a variable will hold, so there are no constraints on the operators or methods you can use, for example:

// JavaScript code
var myvar = "Hello";
myvar += 1;
alert(myvar); // outputs "Hello1"

C# and VisualBasic.NET are strongly typed; however, they both offer a generic object type, for example:

// C# code
object myvar = "Hello";
myvar += 1;

This code will throw a compile-time error; although myvar can be set to anything, the compiler knows that myvar is a string at the point you try to add 1.

The dynamic type introduced in C# 4.0 is subtly different:

// C# code
dynamic myvar = "Hello";
myvar += 1;

The compiler does not check the current state of a dynamic variable so no compile-time errors will occur. However, an exception will be thrown at runtime because 1 is unable to be added to a string.

Dynamic variables effectively inherit the properties and methods appropriate to their type at runtime. The following code will run because myvar is a string at the point the Length property is used, for example:

// C# code
dynamic myvar = "Hello";

Although dynamic variables offer flexibility, there are a number of risks:

  1. No IntelliSence: 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.
  2. No compile-time errors: a non-existent property or method could be used, such as myvar.DoesNotExist(). Your code would still compile and run, but an exception would be thrown when the call is attempted.

I’d suggest you only use dynamic types when there are no other alternatives; for example, when making calls to COM objects with loosely typed APIs (Microsoft Office is a good example) or calling dynamic languages such as Python and Ruby.

  • Don’t do it, Microsoft! Don’t destroy one of your best properties!

Get the latest in Front-end, once a week, for free.