Friday, July 11, 2008

C# Puzzle No. 11 (intermediate)

Generic list type needs an item type to be initialized:

List<int>    listInt;
List<string> listString;

On the other hand, C# 3.0 allows anonymous types to be used in the code. An anonymous type is never explicitely named:

var item = new { Field1 = "The value", Field2 = 5 };
Console.WriteLine( item.Field1 );

How it is then possible to declare a generic list of anonymous type?

var item = new { Field1 = "The value", Field2 = 5; };
List<?> theList = 
    /* how do I make a generic list with item in it 
       so that I can add other items of the same anonymous type?

1 comment:

Anonymous said...

maybe this way ..

var item = new[] { new { Field1 = "The value", Field2 = 5 } }.ToList();

A bit tricky , but hey - it works right? :)

Very interesting C# puzzles you wrote here. Could you please write more? I'm really looking forward.