4

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?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Victor Mukherjee
  • 10,487
  • 16
  • 54
  • 97

2 Answers2

3

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()
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

This may be not what you are asking for, but if you later want to use the DataBoundItem for a row, you can do it this way:

var item = TypeExtensions.CastByPrototype(row.DataBoundItem, new { ch = 'a', length = 0});
//you can use item.ch and item.length here
Trace.WriteLine(item.ch);

with the support of this method:

public static class TypeExtensions
{
    public static T CastByPrototype<T>(object obj, T prototype)
    {
        return (T)obj;
    }
}
deerchao
  • 10,454
  • 9
  • 55
  • 60
  • You can make this a bit more readable by making it an extension method and naming it `CastToTypeOf`. So all this reads: `row.DataBoundItem.CastToTypeOf(new { ch = 'a', length = 0 })`. – nawfal Jun 28 '14 at 16:30