Tutorial :Anonymous Generics - Where would I use this?



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?


Solution:1

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 });  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »