What’s the benefit of generics in an in interface e.g. IEnumerable

I’ve come across a method that requires a parameter that implements IEnumerable and is of a certain type like this:

public myMethod (IEnumerable<HttpPostedFileBase> myParameter) {
                   ....
}

Why do this at all? Why not just implement the IEnumerable interface for HttpPostedFileBase and require the parameter to be an HTTPostedFileBase?

2

Because then IEnumerable<T> can be used for any type T, not just HttpPostedFileBase.

Most of the collections in the System.Collections.Generic namespace implement IEnumerable<T>. IEnumerable<T> was created, not to provide concrete collection implementations for specific types, but to provide concrete implementations of specific kinds of collections that can work with any type.

The following collections all implement IEnumerable<T>, and can therefore perform all of the operations defined by IEnumerable<T>:

Dictionary<TKey, TValue>
HashSet<T>
List<T>
LinkedList<T>
Queue<T>
SortedDictionary<TKey, TValue>
SortedList<TKey, TValue>
Stack<T>
SynchronizedCollection<T>
SynchronizedKeyedCollection<K, T>
SynchronizedReadOnlyCollection<T>

But while they all have different performance and memory characteristics, they’re all still capable of working with objects of any type.

3

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *