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();
}
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With