C# 4.0 New features – Part 1: dynamic type
With C# 4.0 actively in development I thought it would only be appropriate to start writing about the new features. The first I’ll be visiting is the new dynamic type.
The dynamic type allows us to easily access an object type without statically knowing the type at code-time. This means we can declare an object as dynamic at code-time without having to know anything about it. This means we get no intellisense, code-time or compile-time feedback. If a member/method is invoked dynamically that does not exist or something along those lines you will get a runtime exception of type RuntimeBinderException stating it could not find the symbol. In order to allow the dynamic invocation of these members/methods it utilizes some things from the DLR (Dynamic Runtime Library) which actually runs as a normal .NET DLL on top of the CLR (Common Language Runtime). Let’s see it in action.
We’ll start with something simple to get us going.
1: static void Main(string[] args)
2: {
3: dynamic dynObj = "Hello dynamic world!";
4: Console.WriteLine(dynObj);
5: Console.ReadLine();
6: }
As you can see this looks pretty straight-forward. We’re just declaring a dynamic type (dynObj) and setting it as a string type. The output is as follows…
Hello dynamic world!
So you can see that we can treat it like a normal .NET object but with no intellisense or statement completion. Time to check it’s actual type.
1: static void Main(string[] args)
2: {
3: dynamic dynObj = "Hello dynamic world!";
4:
5: Type dynObjType = dynObj.GetType();
6: Console.WriteLine(dynObjType.Name);
7:
8: Console.ReadLine();
9: }
Outputs…
String
Exciting, I know. What this tells us is that at run-time it’s being treated as a string whereas at code-time it’s treated like a dynamic type. Something you can also get out of that code snippet is that I’m calling .GetType() on the object. This could lead to some much more complex uses I just wanted to show the basics
I know my examples weren’t all super-exciting however I showed the basic ideas behind using a dynamic type. Currently dynamic types can be used for generic type parameters, method parameters, method return types and so on. They however have a few limitations on them. For example – you cannot use the addition (+) operator on dynamic objects. In the long run however, they give us much easier access to unknown incoming object types. So instead of having to use reflection to crawl the type you could just use dynamic types instead… quite handy indeed.