On managed something and graphical nonsense

Saturday, September 06, 2008

Anonymous Generic Lists

Kirill Osenkov made a pretty good example on how it is possible to create lists of anonymous types in C# 3.0. I knew about this because of a collegue at work and automatically said... we can do this with every single type, not just anonymous :)

I will just show a slightly different implementation of the List Factory provided by Kirill example:

public static class AnonymousExtensions
{
public static IList<T> ToList<T>(this T item)
{
return new List<T>() { item };
}
}

That implementation use type inference and extensions methods to achieve the following:

static void Main(string[] args)
{
var customer = new {Name="John"}.ToList();
customer.Add( new {Name="Bill"});
}

The interesting side effect is that with that definition we are not only providing the capability to create lists from anonynous types but for any type based on an example. In the next example we are going to use an integer, and create a list based on it.

static void Main(string[] args)
{
var anotherList = 1.ToList();
anotherList.Add(2);
}

I will try to continue writing stuff here and not let the blog dormant for a year (as I did :) ) but I cannot promise anything.

Hope you enjoyed this simple code.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<$I18N$LinksToThisPost>:

Create a Link

<< Home