Somewhere in my code I have an object that I already know that is a list. But I don't know the type parameter of that list. I need to iterate over it's items. I tried to cast that object to a list of objects but it didn't help me:
List<Object> objList = (List<Object>)(dataModel.Value);
foreach (var item in objList)
{
Console.WriteLine(item.ToString());
}
In the above code, the Value
property of dataModel
is a list of XYZ
values, but it throws an exception when I run this code. It says that, it could not cast XYZ
to Object
.
Is that possible to do some deserialization and do the job over deserialized objects?
You should cast to IEnumerable<object>
, or even just IEnumerable
.
A List<string>
is not a List<object>
as generic variance doesn't apply to classes, and a List<string>
is not an IList<object>
as IList<T>
is not covariant. (It can't be, due to operations which accept a T
, such as Add
.)
However, IEnumerable<T>
is covariant in T
which is exactly what you want in this case - but only if your value is a list of reference types; covariance doesn't work with type arguments which are value types... so a List<int>
isn't convertible to IEnumerable<object>
. It is still convertible to IEnumerable
though, so the following code gives you the most flexible solution:
var items = (IEnumerable) dataModel.Value;
foreach (var item in items)
{
Console.WriteLine(item);
}
See more on this question at Stackoverflow