Is there a difference between the interfaces IEnumerable
, ICollection
or IList
?
At what point should each of the interfaces be used in my developments?
Is there a difference between the interfaces IEnumerable
, ICollection
or IList
?
At what point should each of the interfaces be used in my developments?
IEnumerable:
It is located in the System.Collections namespace . There are two interfaces defined: one generic and one non-generic. You can see it in its interface definition:
That the method
GetEnumerator
will return an instance of an object of a class that implements the interfaceIEnumerator
, which implements two methods,MoveNext()
andReset()
. It also has a property calledCurrent
that returns the current item in the list. As a main feature, IEnumerables can be traversed with theforeach
.iCollection
As in the previous one, we also have two definitions, one generic and one not.
The first thing we should pay attention to is that it inherits from
IEnumerable
, so it allows us to use the methods mentioned above. They can also be traversed, but unlike the previous one, this one can be altered.IList
As in the previous two, the library contains two definitions, one generic and one non-generic.
As you can see, when implementing the previous interfaces, you can use their own methods and also your own, which, as we can see, are related to the position.
Now... When should you use each one?
The answer is that it depends on what level of accessibility you need for your code:
@Fran's explanation is excellent and I would like to add something else.
When selecting which type of list to use, in addition to the interface you must select which Collection to use. A collection can implement one or more of the interfaces you mention so the collection implementer can have one or more "abilities" that @Fran mentions.
It is very important to know if you want to store objects of the same type or different types in the collection, that is, save (and only allow) objects of the Person class in the collection or save objects in a collection string, int, Person, dog etc.
In this link https://www.tutorialsteacher.com/csharp/csharp-collection you can see a class chart where you can see how the interfaces and the classes that implement it are related. In this case complementations allow mixing data types. In this other link https://www.tutorialsteacher.com/csharp/csharp-generic-collections mentions which are the collections where they allow to store only elements of the same type.
You can see that ICollection extends the other two interfaces and all the implementations implement this interface so they implement all 3 at the same time. The important thing is that in the method signature you always use one of the interfaces so as not to couple the method to one particular implementation.