There’s a time when new feature or frameworks arise and you get to know them and immediately grasp that new and useful way of doing things, but there are also times when clarity only comes after a bit of blurriness. From what I’ve read, the new Dynamic type in c# 4.0 is currently one of such cases, when compared to var. I read many developers say “What’s the point?” or “Why do I need this?”. Well, I believe it’s a matter of architectural needs, mixed with coding style. To break this discussion into pieces, and because I feel the force is strong with this one
I found myself with the task of enlightening things up a bit.
In fact, this article hopes to settle the dust on this. I’ve seen a number of articles and posts on the web comparing and debating advantages and disadvantages, but I didn’t find them clear or eligible for training purposes. And even after knowing what each one really represent and allow, their usage and necessity is somewhat cloudy. Specially when it comes to dynamic.
So, to get the discussion started, I believe that we first must make sure we understand the basics of each one of these types, and build our structured thinking from there. You all know the System.Object type. Or its alias, object. Everything in the .Net Framework is an object, right? You can even refer to any type as object, by boxing it like this:
//Boxing
object var1 = 23;
// This will produce a compiler error
object sum = 3 + var1;
Since we specified 23 as var1’s value, it will be inferred and internally assumed as System.Int32. However, adding 3 var1 produces an “Operator ‘+’ cannot be applied to operands of type ‘int’ and ‘object’” compiler error.
This is where var comes in handy. If, instead of object we use the var type, the compiler will infer the underlying type and take it into consideration along the method scope. I say method scope because the var type can only be declared inside a method. So, the following would work:
var var2 = 23;
object sum2 = 3 + var2;
You can see the differences when boxing an Int32 value, but the same kind of difference arises when unboxing. Assigning var1 to an int variable produces a compiler error “Cannot implicitly convert type ‘object’ to ‘int’”, suggesting a cast, while assigning var2 compiles successfully:
// Produces compiler error
int var3 = var1;
// Compiles successfully
int var4 = var2;
var is still statically typed though. The only difference is, for instance, that you don’t need to repeat the type upon initialization:
// Type is specified only once
var x = new Collection();
It’s a nice bonus, but not it’s main purpose. The true purpose behind var is so that we can declare a strongly typed variable without needing to know the name of the variable’s type. This is crucial in order to enable C# 3.0’s anonymous types. You wouldn’t be able to declare a variable of an anonymous type if you always had to include the type name as part of the variable declaration. That’s the main reason var has been added to the language.
In some cases, when software architecture enables you to do so, you also have the advantage of changing return types without producing compilation errors.
Consider the following two classes. Event though they are similar in functionality, they are, nevertheless, different types and so, bound to the usual rules:
public class Human
{
public int Age { get; set; }
public string Name { get; set; }
}
public class Dog
{
public int Age { get; set; }
public string Name { get; set; }
public string Breed { get; set; }
}
Now, imagine the following method from any given business layer, that returns a new instance of type Human:
public Human GetInstance()
{
return new Human();
}
And a consumption example:
var o = GetInstance();
o.Name = "Alex";
o.Age = 23;
If, in the future, someone changes GetIntance()’s return type to Dog, you won’t need to change the previous code, because the same rules apply to the new type, since var’s type is implicit. Weird architectural approach, but an advantage to consider nevertheless.
And then there’s the dynamic type. dynamic is a static type, but an object of type dynamic bypasses static type checking. It’s like a type closing the door to the compiler when he knocks asking who’s in. And, as such, you don’t get the usual intellisence information. You’ll simply get the following:

At compile time, an element that is typed as dynamic is assumed to support any operation. He simply doesn’t know what it is, nor where it comes from. You are in control
dynamic var1 = 23;
// Sum operation resolves successfully.
object sum1 = 3 + var1;
// This also works
int var2 = var1;
As you see in the previous snippet, it behaves just like var, but without intellisence. “No intellisence? Why bother then??” – you ask. We’ll get to that shortly. For now, consider the following extended Human class:
public class Human
{
public int Age { get; set; }
public string Name { get; set; }
public void Punch(int intensity)
{
Console.WriteLine(string.Format("Punched with {0} strength.", intensity));
}
}
A typical consumption example would be:
Human h = new Human();
h.Punch(100);
But if we used dynamic, we could do this:
dynamic h = new Human();
h.Punch(100, "Right in the face!");
Even though there’s no corresponding method signature in the Human class, the dynamic type made the compiler became passive, and he didn’t analyze the underlying/resolving type. So the snipped compiles just fine, but resulting in a runtime error later on.
The dynamic type has a broader usage than var. It can be used as a property, field, indexer, parameter, return value, local variable, or type constraint; it can be the target of an explicit conversion and it can be the right side assignment of both is or as operators or typeof argument. The following example demonstrates some of these arguments:
public MainWindow()
{
InitializeComponent();
// Prints ".net Brainwork rocks!" to the output window
Console.WriteLine(ExampleMethod(23));
}
public dynamic ExampleMethod(dynamic number)
{
dynamic dyn;
int num = number;
dyn = (dynamic)num;
string str = ".net Brainwork rocks!";
dyn = (dynamic)str;
return dyn;
}
So what the dynamic type really does is telling the compiler to skip operation analysis and validation at design time, and instead, it resolves the types and operations at runtime. It accomplishes this through a new engine called Dynamic Language Runtime. The dynamic language runtime (DLR) is a new .Net Framework 4.0 runtime environment that adds a set of services for dynamic languages to the common language runtime (CLR). The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages. IronRuby and IronPython are two examples of languages developed by using the DLR.
Dynamic languages can identify the type of an object at run time, whereas in statically typed languages such as C# you must specify object types at design time.
The purpose of the DLR is to enable a system of dynamic languages to run on the .NET Framework and give them .NET interoperability. The DLR introduces dynamic objects to C# and Visual Basic in Visual Studio 2010 to support dynamic behavior in these languages and enable their interoperation with dynamic languages.
So, all in all, dynamic has an entirely new operation going on. It’s not just a matter of making it easier for developers to produce code or improve its quality, but it’s a new system for dynamic type handling, that improves how the language interacts with external data objects or services, whose types are only known at runtime like COM.
References:
Dynamic Language Runtime Overview – MSDN