1

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 IEnumerable<T> can be used for any type, not just HttpPostedFileBase. That's generally true for the concrete implementations of IEnumerable<T> such as List<T> and Dictionary <Tkey, TValue>. In other words, you don't need a concrete implementation of each of these collections for every possible type; you only need one implementation for all types. – Robert Harvey Apr 15 '16 at 1:47
  • Also, it gives your caller more flexibility. If you make your type enumerable, you have to supply the way for your caller to add multiples to it. If you use IEnumerable<T>, you leave your caller free to pass a List<T> or a HashSet<T> or a Queue<T> or a Stack<T> or a host of other things. This lets your caller choose what's best for his/her circumstances. – Kyralessa Apr 15 '16 at 4:41
5

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.

  • Doh. Thanks Robert. Yes, that answers the question so I'll mark it as such. You've helped me recognise what my real question should've been! It's here - programmers.stackexchange.com/questions/315784/… – Chris Halcrow Apr 15 '16 at 3:30
  • That question no longer exists. I guess you realized that you can call SaveLogo with any concrete instantiated type that implements IEnumerable<T>. – Robert Harvey Apr 15 '16 at 3:34
  • Yeah, thanks Robert, I was being a dumdum. I was misreading the code but you've clarified things with your answer. Obviously what the method expects is a concrete instance of anything that implements IEnumerable and that contains items of type HttpPostedFileBase - that's what I missed! – Chris Halcrow Apr 15 '16 at 3:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.