Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning IEnumerable with "ToListAsync()" inside the method [closed]

Tags:

c#

.net

Currently I am working with some one else's code. And this is not the first time when I see something like this:

public async MyMethod Task<IEnumerable<MyResult>> FindResults()
{
// some code here
var ret = await repository.BusinessObjects.ToListAsync()

return ret;

}

my question is: Isn't it counterproductive to use IEnumerable in MyMethod return type because the result has been enumerated already and it's better to keep it this way? Wouldn't it be better to use List ?

(I guess it also applies to non-async operations, but I decided to show this the way I see it in the code I working with just in case)

like image 705
agfc Avatar asked Apr 06 '16 16:04

agfc


1 Answers

Technically speaking there is no problem with writing code this way. In your specific code example above it does not matter (technically) if you are returning a List<> instance but the method's return type is IEnumerable<>. There is no performance hit, the actual returned type is still a List<>.

That being said it is not good practice. There is a design guideline that states you should structure your methods to always return the most specific type possible AND accept the most generic/abstract type possible (within limitations of course, you should not take object as a parameter for each method).

See this article titled Return the most specific type, accept the most generic type by Vladimir Khorikov as a reference. This has also been asked on SO before, see Is it better to return the most specific or most general type from an action method?.

So this would mean the following 2 signatures would be good practice (using your example) assuming that the 1st signature a List<MyResult> is the actual returned type and in the 2nd example that whatever is doing the updating just needs to iterate over the input.

public async Task<List<MyResult>> FindResultsAsync();
public async Task UpdateAsync(IEnumerable<MyResult> itemsForUpdate);
like image 158
Igor Avatar answered Sep 28 '22 05:09

Igor