Cast List of Anonymous type to List of Dynamic Objects

John Isaiah Carmona picture John Isaiah Carmona · Apr 24, 2013 · Viewed 40.5k times · Source

Why can't I cast a List<AnonymousObject> to a List<dynamic>? I have this following code:

var datasource = someList.Select(o => new { x = o.A, y = o.B });
dgvSomeGridView.DataSource = datasource.ToList();
dgvSomeGridView.DataBind();

Then I access the GridView.DataSource with the following code:

var ds = ((List<dynamic>)dgvSomeGridView.DataSource);
....

But it throws an error on the line where I cast it to List<dynamic>, it says:

Unable to cast object of type System.Collections.Generic.List'1[<>f__AnonymousType0'8[System.Int32,System.String]] to type System.Collections.Generic.List'1[System.Object].

Why can't I cast a list of anonymous type to a dynamic, or as the error says to an object type? How can I resolve this?

My Code is in C#, framework 4.0, build in VS2010 Pro, platform is ASP.NET.

Please help, thanks in advance.

Answer

cuongle picture cuongle · Apr 24, 2013

Since List<T> is in-variant, not co-variant, so you have to cast into IEnumerable<dynamic> which supports co-variant:

var ds = ((IEnumerable<dynamic>)dgvSomeGridView.DataSource).ToList();

For more information about covariant