According to this MSDN reference
IEnumerable is covariant and this is possible to implicitly cast a list of objects to an enumerable:
IEnumerable<String> strings = new List<String>();
IEnumerable<Object> objects = strings;
In my own code i have written a line of code that works perfect when item type of the list is class
Point (Point is a simple class with three properties double x,y,z):
var objects = (IEnumerable<object>)dataModel.Value;
// here property Value is a list that could be of any type.
But the above code returns the following exception when item type of the list is
Unable to cast object of type System.Collections.Generic.List1[System.Double]
to type System.Collections.Generic.IEnumerable1[System.Object].
What is the difference between
double and what causes the code to work with
string but not with
According to this post we could simply cast a list to
IEnumerable (without type argument) so as I only need to iterate over items and add new items to the list ( Actually I do not need to cast items of the list, at all). I decided to use this one:
var objects = (IEnumerable)dataModel.Value;
But if you need to cast items of the list to
object and use them, the answer from Theodoros is the solution you most follow.