Stupid question 41: Should I use IList or List?
Should I use List or IList?
Out of habit I’ve been using interfaces when working with collections, using the one with bare minimum of what I need. Except for the constant reminders from refactoring tools I might have installed, I also have a vague recollection of being told to do so by a skilled developer when I did my first (kind of) internship. But a few days ago this question came up at work, and I thought it was about time to check whether my thinking around this was right or not. So I spent a little time finding out, should I use an interface or the concrete implementation?
So, again, as with the last discussion - I’ll gladly change my mind if I am wrong on this one so please give me those really valuable comments below!
I always choose to use the interface with the bare minimum that I need, I rarely use IList, IEnumerable seems to be my favorite, but there are times when I do need the extra functions that come with IList. And I know this is something not everybody agrees on, but in a method I tend to return the same thing as I take in when it comes to collections. In other words, if I take an IEnumerable I’ll return an IEnumerable. I do this even in the smallest of projects, it’s just a habit I’ve gotten into and I like to be consistent.
But I might be wrong on this one, so I’m passing the question to you, IList or List? IEnumerable or IList? And does the type of project matter (exposed vs unexposed code)?
Last modified on 2012-09-10