How to Use Dynamic Types in C# 4.0

Share this article

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;
Console.WriteLine(myvar);

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;
Console.WriteLine(myvar);

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";
Console.WriteLine(myvar.Length);

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.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

.NETASP.NETC
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week