Reputation: 137
I have defined a function: public IEnumerable<User> GetAllUsers()
The logic of that function goes something like this:
var userList = new List<User>
.. logic ...
return userList;
Is there a benefit of defined returning type IEnumerable<User>
or should I just be plain about it and define return List<User>
type?
Upvotes: 3
Views: 3158
Reputation: 38094
As Guidelines for Collections said:
DO use
ReadOnlyCollection<T>
, a subclass ofReadOnlyCollection<T>
, or in rare casesIEnumerable<T>
for properties or return values representing read-only collections.In general, prefer
ReadOnlyCollection<T>
. If it does not meet some requirement (e.g., the collection must not implementIList
), use a custom collection by implementingIEnumerable<T>
,ICollection<T>
, orIList<T>
. If you do implement a custom read-only collection, implementICollection<T>.IsReadOnly
to return true.In cases where you are sure that the only scenario you will ever want to support is forward-only iteration, you can simply use
IEnumerable<T>
.
and DO NOT use ArrayList or List in public APIs:
These types are data structures designed to be used in internal implementation, not in public APIs. List is optimized for performance and power at the cost of cleanness of the APIs and flexibility. For example, if you return List, you will not ever be able to receive notifications when client code modifies the collection. Also, List exposes many members, such as BinarySearch, that are not useful or applicable in many scenarios. The following two sections describe types (abstractions) designed specifically for use in public APIs.
Upvotes: 0
Reputation: 9804
Every collection can be implicitly converted into a IEnumerable. Indeed that happens every time you feed one to a foreach-loop. foreach only works with Enumerables. To the annoyance of everyone that runs into this Exception case: Unable to remove list item from list inside a for each loop C#
As you are propably finish filling the List before returning, I see no advantage to Enumerables. What they are really good at, is hiding asynchronous data retreival of some sort from the consumers. Retreival that happens while the Enumerable is in use. See Directory.EnumerateFiles() for a practical example.
List<T>
is more universal. If someone needs a IEnumerable<T>
, they can make one from it, without relevant amount of work.
Upvotes: 1
Reputation: 62472
It will depend. It's always best to return the most restrictive type possible, but the issue with IEnumerable
is that it's typically not meant to be enumerated more than once. For example, the IEnumerable
may be selecting from a database, and each enumeration will start a potentially long running query.
In your case, if you're looking to return information about the user then I'd consider a IReadOnlyList
or a IReadOnlyCollection
Upvotes: 3