Essential C# Anonymous types  Suggest an edit

Instantiating generic types with anonymous types

Using generic constructors would require the anonymous types to be named, which is not possible. Alternatively, generic methods may be used to allow type inference to occur.

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, implicitly typed arrays may be converted to a List through the ToList LINQ method:

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

Table Of Contents
22 Enum
25 GUID
34 Anonymous types
107 Stream
108 Timers
  ↑ ↓ to navigate     ↵ to select     Esc to close