Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics and anonymous type

Tags:

c#

generics

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" });
like image 286
user274364 Avatar asked Jan 20 '26 03:01

user274364


2 Answers

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.

like image 78
Tomas Petricek Avatar answered Jan 21 '26 17:01

Tomas Petricek


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);
like image 33
JaredPar Avatar answered Jan 21 '26 17:01

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!