How to Use Dynamic Types in C# 4.0
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.