I tried to make a conversion from object (the object contains a List<Apple>
) to List<object>
, and it fails with an exception:
Unable to cast object of type 'System.Collections.Generic.List[list_cast_object_test.Apple]' to type 'System.Collections.Generic.List[System.Object]'.
When I have replaced List
with IEnumerable
or IList
(an interface) it works well, and I don't understand the difference....
The code looks like:
private void Form1_Load(object sender, EventArgs e) {
object resultObject = GetListAsObject();
// this cast works fine, it's normal...
var resAsIt = (List<Apple>)resultObject;
// also when I use a generic interface of 'object' cast works fine
var resAsIEnumerable = (IEnumerable<object>)resultObject;
// but when I use a generic class of 'object' it throws me error: InvalidCastException
var resAsList = (List<object>)resultObject;
}
private object GetListAsObject() {
List<Apple> mere = new List<Apple>();
mere.Add(new Apple { Denumire = "ionatan", Culoare = "rosu" });
mere.Add(new Apple { Denumire = "idared", Culoare = "verde" });
return (object)mere;
}
}
public class Apple {
public string Denumire { get; set; }
public string Culoare { get; set; }
}
Someone may explain me what it happens? What is the difference between cast to a generic interface and cast to a generic class?