Reputation: 1171
My Question might feel a little stupid but i really want to know why was the collection hierarchy designed in such a way that it contains Interfaces and classes whereas it could have been only classes or just one interface at the top and rest classes.
Can someone explain me the reason?
Upvotes: 0
Views: 82
Reputation: 3820
Each class can be derived from only one class but multiple interfaces.
Why do we need multiple interfaces?
Generally there are two reasons that we have multiple Interfaces for one class, 1. One class can have different types of behaviors, 2. Open-Closed Principle.
A short definition for Interface is: Interface is an entity that determines how the derived classes must behave, and since there are different types of behaviors, we need possible different Interfaces for each class.
Moreover, according to the 2nd principle of SOLID which is short for Open-Closed Principle, meaning that entities must be open for extensions but closed for modifications, even if you want to add a new behavior (e.g. CanBark
) to a specific class and you already have a relevant Interface (IDogActions
) for that as a parent of your class, it is recommended not to modify The IDogActions
Interface, because there might be many other classes implementing this Interface and don't need the new action, instead you can create a new Interface (e.g. IDogAuditoryActions
).
Upvotes: 1
Reputation: 1407
Think, if you only define an IList
interface then you need classes to implement it. List
is just one such implementation, a default if you will.
On the other hand if you only had a list as abstract class (i.e. without an IList
interface) then all your custom list collection classes would have to inherit. I would say it would have been a bad design choice, as the members of IList
are more suited for contracts (individual add/remove methods can have different implementations, e.g. priority list, etc.). By making List available as an abstract class you would be forcing and controlling people's design choice.
Also in C# you would be additionally constraint to not be able to inherit from any other class for your custom collections.
Basically you should try and see the different features offered by an interface and an abstract class. That would make you realize the difference between IList and List.
Upvotes: 1