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
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:
- 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.
- 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 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.