I am trying to write my own generic collection (List<T>
) in C# but got confused with the interfaces. As I understand, in order to create my own collection, I need to implement several interfaces, like ICollection, IList, IEnumerator, IEnumerable etc. But I can't really understand which ones I need.
Thanks in advance
You have to implement IList<T>
for access to the collection's items by their index. IList<T>
inherits from ICollection<T>
, IEnumerable<T>
and IEnumerable
, so you get those anyway.
For a more basic collection without access to an item by index, you implement ICollection<T>
, which comes with IEnumerable<T>
and IEnumerable
through inheritance.
You can additionally implement IReadOnlyList<T>
(or IReadOnlyCollection<T>
respectively), but that is usually not necessary.
You should also look into inheriting from System.Collections.ObjectModel.Collection<T>
instead, which is the recommended way, because the usual boilerplate interface implementations are already done for you and you can concentrate on the parts that make your collection special.