danze
danze

Reputation: 765

Conversion of list of nullables to list of objects

Why is the second conversion failing with

InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List`1[System.Nullable`1[System.Boolean]]' to type 'System.Collections.Generic.IEnumerable`1[System.Object]'.
object list1 = new List<string>() { "a", "b" };
object list2 = new List<bool?>() { true, false };

IEnumerable<object> bind1 = (IEnumerable<object>)list1;
IEnumerable<object> bind2 = (IEnumerable<object>)list2;

Any ideas would be appreciated.

Upvotes: 3

Views: 1619

Answers (2)

RoadieRich
RoadieRich

Reputation: 6566

See Jon Skeet's answer for the reasons, he'll explain it far better than I ever could.

The easiest fix is to use the Enumerable.Cast<T>() extension method:

using System.Linq;

object list1 = new List<string>() { "a", "b" };
object list2 = new List<bool?>() { true, false };

IEnumerable<object> bind1 = list1.Cast<Object>();
IEnumerable<object> bind2 = list2.Cast<Object>();

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1501033

Nullable<T> is a value type, and generic covariance doesn't apply for value types (so there's no conversion from IEnumerable<int> to IEnumerable<object> either, for example):

Variance applies only to reference types; if you specify a value type for a variant type parameter, that type parameter is invariant for the resulting constructed type.

The simplest fix would be to use Cast:

IEnumerable<object> bind2 = list2.Cast<object>();

Upvotes: 7

Related Questions