Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why List<> implements RemoveAll, but IList<> does not

Tags:

c#

list

I'm refactoring my code to use IList instead of List. I used List.RemoveAll in a couple of places, and noticed that IList does not have this method at all. Is there any good reason for this?

like image 297
Sergey Kandaurov Avatar asked Aug 09 '15 10:08

Sergey Kandaurov


1 Answers

There is a principle in software engineering called interface segregation. It boils down to the notion that smaller interfaces are better than larger ones. When this idea is taken to the extreme, the ideal interface declares only one member - but let's not bother with that. The point is that interfaces should describe strict requirements, not convenience features.

In our specific case, the IList<T> interface declares the members that a type is required implement in order to be an IList<T>. Obviously, a type isn't required to implement RemoveAll in order to be an IList. It is convenient for a type to do so, but it's not required.

This is a valid use case for extension methods, though. You can define your own RemoveAll extension method for any IList<T> and keep the convenience.

like image 181
Theodoros Chatzigiannakis Avatar answered Nov 15 '22 16:11

Theodoros Chatzigiannakis