A function that causes code to be interrupted due to its absence is called general type covariance. C # supports dispersion in generics , but only in interfaces (and not in specific classes).
The foreach snippet works because it treats Fruitlist as an IEnumerable<Fruit> , and since it is a common interface with a parameter of type out (covariant), the compiler can view it as an IEnumerable<Resource> .
If getListOf permissible for getListOf to return an IEnumerable<Resource> , then changing the signature of the function will compile the code. Otherwise, the compiler cannot guarantee type safety, because you can write this code:
List<Resource> apples = this.getListOf("apple"); apples.Add(new Orange());
Another option is to return a non-generic type, in which case the type safety will be lost again, and the compiler will introduce runtime checks to make sure that you do not mix apples with oranges (but at least the code should work if it works well leads.)
source share