Wednesday, May 20, 2009

C# 4.0 Dynamic Type... Something useful.

Here's something that's been on my wishlist for quite some time. I've always hated the fact that my anonymous types can't be used outside of their method scope. If I create an IEnumerable of anonymous type variables, and I want to use them outside of their created domain, I previously had very few options:

1. Give up the anonymous type and write a class to hold the data.
2. Use reflection. This works, but it's a little slow.
3. Use an Expression Tree. This also works, but creating an Expression tree can be a tedious and difficult process.

Now, in C# 4.0 with the dynamic type, I can finally call properties on my anonymous types outside of their scope. Consider the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
class Program
static void Main(string[] args)
foreach (dynamic d in GetValues())
Console.WriteLine("{0} is {1} years old", d.Name, d.Age);

static IEnumerable<dynamic> GetValues()
Dictionary<string, int> result = new Dictionary<string, int>();
result["David"] = 30;
result["Jennifer"] = 25;
foreach (var item in result)
yield return new { Name = item.Key, Age = item.Value };

Now, what this code does, is yields an IEnumerable of anonymous types, which are then used outside the method scope in the Main method -- a feat only accomplished through the use of the dynamic type.

While this is convenient, there are a couple of things to keep in mind:

1. This is still going to have the same major drawback of either reflection or expression trees. Though it looks strongly typed, it's not. If I change Name to FirstName, for example, my code would still compile, but I'd get a runtime error when I tried to run the application.
2. I get no Intellisense for dynamic types. Typically, this means I should only use the keyword in situations where I'm coding close to the type declaration.

That being said, this is still a wonderful new feature, and I'm looking forward to exploring more over the next years.