Tuesday, September 13, 2011

Passing objects of anonymous types as parameters to method

One of the underpinnings of LINQ is anonymous types. When you use a projection (i.e. select) you can choose to return data as an anonymous type. However, you are constrained by the fact that you can't pass that data out of this method because the type is anonymous. A consequence of this is that a method with LINQ in it can become bloated due to not being able to pass anonymous data out. A solution to this problem is that you can use the dynamic keyword to allow you to pass out this dynamic object. This object will be read-only. Here is a small example of that.
 void Main()

{

dynamic foo;

var bar = new { name = "John", title="code monkey"};

var bar2 = new { name = "John", title="junior code monkey"};

foo = bar;

WriteIt( foo);

WriteIt(bar2);

}

static void WriteIt( dynamic dynamo)

{

Console.WriteLine(dynamo.title);

}

One important gotcha with using dynamic typing is that extension methods aren't currently available. That is a real shame since these two techniques would go together naturally for more ruby-esque development. But at some point, if you really want or need to program with dynamic techniques in .NET you are better of with IronRuby or IronPython. Sadly, Microsoft's interest in the DLR appears to have waned after successfully making programming for Microsoft Office easier in .NET. You can perform a cast though, but only if your type is not anonymous.

No comments:

Post a Comment