Reputation: 1381
I recently discovered a trick using casting by example to instantiate a generic with an anonymous type.
http://brendanjerwin.com/blog/2009/03/19/anonymous-generics/
So, its a neat trick, but when would it be used? Any ideas?
Upvotes: 4
Views: 424
Reputation: 754853
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 });
}
Upvotes: 5