Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of list of nullables to list of objects

Tags:

c#

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.

like image 485
danze Avatar asked Jan 24 '26 04:01

danze


1 Answers

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>();
like image 69
Jon Skeet Avatar answered Jan 26 '26 16:01

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!