Christos
Christos

Reputation: 53958

method signature pass parameter as IEnumerable<T> or as List<T>

The language I use is C#.

As I have read, it is better if a method of an object returns an enumerable type like a list, to state it its signature as bellow:

private IEnumerable<int> listOfNumbers()
{
   // here goes the code of the method
}

rather than

private List<int> listOfNumbers()
{
  //  here goes the code of the method
}

Let now that we want to pass as a parameter a list of objects of type A.

When we write

private IEnumerable<int> listOfNumbers(List<A> list)
{
  // here goes the code of the method
}

it is easier to access the elements of the list and do any calculations with them rather than writing

private IEnumerable<int> listOfNumbers(IEnumerable<A> list)
{
    // here goes the code of the method.
}

In the second case, in order to access the elements of the list, that implements the interface IEnumerable, we should convert the list to a List, inside the code of the method.

I am bit confused about the best way to pass as a parameter a type tha implements the IEnumerable interface. What's the best approach between the above two? Is there any better way?

Thanks in advance for any help.

Upvotes: 2

Views: 4477

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236278

That depends on the way you are going to use your parameter in your method. If you are going to enumerate it, then passing IEnumerable<T> is a good choice. If you are going to add/remove items, then it should be of IList<T>, ICollection<T> or List<T> type.

Try not to give your method more knowledge, then it needs to fulfill it's responsibilities. But also don't give it less knowledge, because it will not be able to fulfill its responsibilities :)

One more sample - should you pass IList<T> or IEnumerable<T> if you need count of items in your method? With list you can use Count property. With enumerable you have Count() extension method. Correct answer is - pass count of items, if count is all you need.

Upvotes: 11

Related Questions