Question

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?

Was it helpful?

Solution

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 });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top