c# - Why does the explicit conversion of List<double> to IEnumerable<object> throw an exception? -


according msdn reference ienumerable covariant , possible implicitly cast list of objects enumerable:

ienumerable<string> strings = new list<string>(); ienumerable<object> objects = strings; 

in own code have written line of code works perfect when item type of list class point (point simple class 3 properties double x,y,z):

var objects = (ienumerable<object>)datamodel.value; // here property value list of type.  

but above code returns following exception when item type of list double:

unable cast object of type system.collections.generic.list1[system.double]  type system.collections.generic.ienumerable1[system.object]. 

what difference between string , double , causes code work string not double?

update

according this post cast list ienumerable (without type argument) need iterate on items , add new items list ( not need cast items of list, @ all). decided use one:

var objects = (ienumerable)datamodel.value; 

but if need cast items of list object , use them, answer theodoros solution follow.

constructed types of variant interfaces (such ienumerable<out t>) variant reference type arguments, because implicit conversion supertype (such object) non-representation-changing conversion. why ienumerable<string> covariant.

constructed types value type arguments invariant, because implicit conversion supertype (such object) representation-changing, due the boxing that's required. why ienumerable<double> invariant.

see relevant documentation:

variance applies reference types; if specify value type variant type parameter, type parameter invariant resulting constructed type.

a possible workaround use linq cast:

var sequence = list.cast<object>(); 

this first check whether source assignment-compatible ienumerable<tresult> trying cast to.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -