Search code examples
c#.netlinqanonymous-typestypeinitializationexception

How to specify the type of an anonymous type while using a generic type


The title is pretty confusing. I will try to explain with an example. Consider the code below:

String[] str={"Apple","Banana","Cherry","Orange"};
var anoCollection=from e in str select new
                                         {
                                          ch=e[0],
                                          length=e.Length
                                         }
dataGridView.DataSource=anoCollection.ToList(); //TypeInitializationException

I feel that I need to mention the type in above case for the ToList<T>() method. But how can I mention an anonymous type here?


Solution

  • It is never possible to mention an anonymous type directly, but you should not need to. Generic type inference means that you don't need to specify the <T> in .ToList<T>() - the compiler will automatically inject the invented type.

    There are only a few ways to refer to an anonymous type:

    • via someObj.GetType(), where someObj is an instance of an anonymous type
    • via generics, as a T, by calling a generic method via generic type inference (as in ToList())
    • various other usages of reflection, pulling in the T via GetGenericTypeParameters()