I was wondering , why does IEnumerable<T> has ONLY the out and not the in contravariant flag ?
public interface IEnumerable<out T>
I can understand the out by this example :
IEnumerable<string> strings = new List<string>(){"a","b","c"};
IEnumerable<object> objects = strings;
object is bigger than string , so the compiler afraid that well do something like:
objects = objects.First().Select(x=>5);// ( we cant insert int to string...)
fine and understood.
but what about if i want to use the IEnumerable as insertion?
something like :
IEnumerable<object> objects = ...;
IEnumerable<string> strings = objects
so i can also INSERT into objects …
but the problem is that there is no IEnumerable<in T> …
am I missing something here?
You can’t insert into
IEnumerable. There is, unfortunately, no “IInsertable”.There is no interface to tell that you can only add items to a collection. This would be an
ingeneric type. Because you can get the items on every collection interface, it is not possible to haveingeneric arguments.Edit
The interface
IEnumerable<T>has only getters, so you can’t insert any elements to the collection using that interface. Because of that,outis allowed in the declaration ofIEnumerable<out T>. It tells the compiler, that values of typeTare only going in one direction, the are “coming out”. This makes it compatible in one direction. You can useIEnumerable<string>as anIEnumerable<object>, because you are only reading from it. You can read a string as an object. But you couldn’t write to it, you couldn’t pass an object as a string. It might be an integer or any other type.