Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using IEnumerable<T> type in parameter of method

Previously I used IEnumerable<T> type, if I passed collection as parameter of method.

But recently, I had a problem with the collection of type IEnumerable<T> that was created in similar way:

var peoples = names.Select(name => new People(name));

In this case, always, if I use a collection peoples (for example, foreach), it creates new instance of class People, and it can easily cause an error.

So I want to ask whether it is right to use the IEnumerable <T> type parameter. I think it may cause problems (see example above) and this type should not be used. What alternatives do you recommend (ICollection<T>, IList<T> etc.) and when to use which alternative?

Or do you think that this is a silly question, because the creation of objects in the Select method uses only a fool?

Of course, I know that I can use ToArray() or ToList() and thus solve the problem. But someone else who uses this method, it can not know. I would like to know how to prevent this by selecting the correct type parameter. List or array is too specific for me when I want to just "enumerate" objects.

like image 924
mveith Avatar asked Jan 17 '23 01:01

mveith


1 Answers

IEnumerable is not a collection. It is just something that you can "enumerate". The problem is not passing IEnumerable to your method, the problem is that if you are using LINQ (Select method), every time you read the enumerable it will execute the code again. If you only want to have it executed once, you can use the ToArray() or ToList() methods:

var peoples = names.Select(name => new People(name)).ToList();

Like this you can still pass it to any method accepting an IEnumerable (or List) and it will only create one instance for each person.

Edit: Your method shouldn't worry about these kind of problems. It's the callers problem. There might be perfectly good reasons to call your method with an enumerable instead of a list. The caller should know that the enumerable gives different results if he passes it to different methods, so you shouldn't worry about that.

The only exception is if you enumerate the parameter more than once in the method itself. In this case you should cache the parameter in a list inside the method and then enumerate the list instead as many times as you need.

like image 127
aKzenT Avatar answered Jan 26 '23 00:01

aKzenT