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?
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:
someObj.GetType()
, where someObj
is an instance of an anonymous typeT
, by calling a generic method via generic type inference (as in ToList()
)T
via GetGenericTypeParameters()