What is the difference between Cast List <object> and Cast IEnumerable <object>

I tried to make a conversion from an object (the object contains List<Apple>) to List<object>, and it failed with an error:

Cannot pass an object of type "System.Collections.Generic.List [list_cast_object_test.Apple]" to enter "System.Collections.Generic.List [System.Object]".

When I replaced Listwith IEnumerableor IList(interface), it works well, and I do not understand the difference ....

The code looks like this:

    private void Form1_Load(object sender, EventArgs e) {
        object resultObject = GetListAsObject();

        // this cast works fine, it 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; }
}

Can anyone explain to me what this is? What is the difference between casting to a common interface and casting to a generic class?

+4
2

IEnumerable<T> - , T ( IEnumerable<out T>, out), T , IEnumerable<object List<Apple>.

List<Apple> List<object>, List<Apple>, List<object>. List<T> , .

+4

, IEnumerable<T> T , List<T> T .

#

- , ToList<T>(), , :

 List<object> result = resultObject.ToList<object>();

List<Apple> List<Object> - List<T>, T Object, List<Apple> List<Object>.

Object Object, strcuts .

+6

Source: https://habr.com/ru/post/1627142/


All Articles