Instantiating generic types with anonymous types

suggest change

An anonymous type has no name you can write in new List<ThatType>(). A generic method can infer the type argument instead.

var anon = new { Foo = 1, Bar = 2 };
var anon2 = new { Foo = 5, Bar = 10 };
List<T> CreateList<T>(params T[] items) {
    return new List<T>(items);
}

var list1 = CreateList(anon, anon2);

In the case of List<T>, implicitly typed arrays may be converted to a List<T> through the ToList LINQ method:

var list2 = new[] {anon, anon2}.ToList();

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents