Sobes.tech
Junior — Middle

Can you name different ways to implement collection interfaces in programming languages?

sobes.tech AI

Answer from AI

In C# interfaces for collections are implemented in various ways depending on requirements:

  • Using standard collections: For example, List<T>, Dictionary<TKey,TValue>, HashSet<T> implement interfaces like IEnumerable<T>, ICollection<T>, IList<T> etc.

  • Implementing custom collections: You can create a class that implements the required interface, for example, IEnumerable<T> for enumeration support, or ICollection<T> for add/remove support.

  • Inheriting from base classes: For example, from Collection<T> or ObservableCollection<T> to extend functionality.

  • Using wrappers: For example, ReadOnlyCollection<T> to create immutable collections.

Example of implementing a simple enumerable class:

class MyCollection<T> : IEnumerable<T>
{
    private List<T> items = new List<T>();

    public void Add(T item) => items.Add(item);

    public IEnumerator<T> GetEnumerator() => items.GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}