Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use an interface like IEnumerable, or a concrete class like List<>

I recently expressed my view about this elsewhere* , but I think it deserves further analysis so I'm posting this as its own question.

Let's say that I need to create and pass around a container in my program. I probably don't have a strong opinion about one kind of container versus another, at least at this stage, but I do pick one; for sake of argument, let's say I'm going to use a List<>.

The question is: Is it better to write my methods to accept and return a high level interface such as C#'s IEnumerable? Or should I write methods to take and pass the specific container class that I have chosen.

What factors and criteria should I look for to decide? What kind of programs work benefit from one or the other? Does the computer language affect your decision? Performance? Program size? Personal style?

(Does it even matter?)

**(Homework: find it. But please post your answer here before you look for my own, so as not bias you.)*

like image 631
Euro Micelli Avatar asked Nov 27 '22 19:11

Euro Micelli


1 Answers

Your method should always accept the least-specific type it needs to execute its function. If your method needs to enumerate, accept IEnumerable. If it needs to do IList<>-specific things, by definition you must give it a IList<>.

like image 66
Rex M Avatar answered Dec 10 '22 13:12

Rex M