Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return IEnumerable<T> or convert to List<T> immediately?

Tags:

c#

ienumerable

I'm designing a class with several functions returning lists of objects. I noticed that debugging becomes easier when my IEnumerable<T> is converted to a List<T> since the objects can be viewed in the Watch window. However, I'm not sure if this is best practice when it comes to IEnumerable.

Q: Which is better?

public IEnumerable<MyData> GetData()
{
    return Foo();
}

public IEnumerable<MyData> GetData()
{
    return Foo().ToList();
}
like image 524
l33t Avatar asked Sep 15 '25 05:09

l33t


2 Answers

Good practice - don't do work unless there are good reasons/required. So unless you have special reasons - just return IEnumerable<MyData> without calling ToList()/ToArray() on it.

Potential reasons:

  • function promises to complete evaluation of potentially delayed enumeration
  • you expect result to be enumerated multiple times
like image 57
Alexei Levenkov Avatar answered Sep 16 '25 19:09

Alexei Levenkov


I'ts better to use a list of elements in case you are using a unit of work that will be disposed, because once its disposed you will not be able to get your elements after.

In all other cases its ok to return the generic IEnumerable, because it offers better flexibility.

In the end it all comes down to your requirements, note that IEnumnerable does not retrieve the elements at the exact moment of assignment to a variale but rather when enumerated.

like image 38
Freeman Avatar answered Sep 16 '25 19:09

Freeman