user274364
user274364

Reputation: 1857

Generics and anonymous type

I understood,normally generics is for compile time safe and allow us to keep strongly typed collection.Then how do generic allow us to store anonymous types like

List<object> TestList = new List<object>();
TestList.Add(new { id = 7, Name = "JonSkeet" });
TestList.Add(new { id = 11, Name = "Marc Gravell" });
TestList.Add(new { id = 31, Name = "Jason" });

Upvotes: 3

Views: 1298

Answers (3)

Tomas Petricek
Tomas Petricek

Reputation: 243126

Others already explained why your code works - your example is strongly typed, because everything is an object, but that means that it's not very useful. You cannot take elements from the list and access for example their Name property, because they are just object, so this cannot work in general.

However, it is possible to create a strongly typed List of anonymous types - it just needs to be done using a small utility method like this:

static List<T> CreateList<T>(params T[] items) {
  return items.ToList();
}

The problem is that you can't call a constructor without providing the name of the type. When calling a method, C# can infer the type parameter, so you can write this:

var testList = CreateList(
  new { id = 7, Name = "JonSkeet" },
  new { id = 11, Name = "Marc Gravell" });
testList.Add(new { id = 31, Name = "Jason" });

This is perfectly type-safe and you can for example write testList[0].Name to get the name of the first person. If you try writing something like testList.Add(42), you'll get a compile-time error, because the list is strongly typed to contain only anonymous types with id and Name properties.

Upvotes: 9

JaredPar
JaredPar

Reputation: 755457

This works because object is the root type of all instances in .Net. Hence anything expression can be used for a location expecting an object because they all meet the basic contract of System.object.

For example the following is completely legal.

List<object> TestList = new List<object>();
TestList.Add(new { id = 7, Name = "JonSkeet" });
TestList.Add("Foo");
TestList.Add(42);

Upvotes: 8

Adam Wright
Adam Wright

Reputation: 49386

Because everything is (or can be boxed into) an object, and that's a List of objects.

Upvotes: 6

Related Questions