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.