views:

195

answers:

1

I recently discovered a trick using casting by example to instantiate a generic with an anonymous type.

http://brendanjerwin.com/development/dotnet/c-sharp/2009/03/19/anonymous-generics.html

So, its a neat trick, but when would it be used? Any ideas?

+4  A: 

The primary place I use this trick is for creating a collection container for anonymous types.

public static List<T> CreateListOfAnonymous<T>(T unused) {
  return new List<T>();
}

Usage:

public void Foo() {
  var list = CreateListOfAnonymous(new { Name = String.Empty, Age = 42 });
  list.Add(new { Name = "foo", Age = 28 });
}
JaredPar
Did I miss something? The second half doesn't seem to use the first half.
John Feminella
var list = CreateListOfAnonymous(new { name = String.Empty, Age = 42 }};
Pontus Gagge
@John, you didn't miss anything. I simply forgot to use it :(
JaredPar