-1

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

Oleg Ivanytskyi
  • 959
  • 2
  • 12
  • 28

2 Answers2

1

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.

Sefe
  • 13,731
  • 5
  • 42
  • 55
0

What is your collection for? If you implement IEnumerable<T> (which entails implementing IEnumerable, then you've an enumerable object. If you've also got an Add() method then you've got an enumerable object that works with collection initialisation. Beyond that, look at the common collection interfaces and ask if they are useful to your use cases, particularly ICollection<T> (adding and removal in particular) and IList<T> (indexing in particular).

Jon Hanna
  • 110,372
  • 10
  • 146
  • 251