Reputation: 14075
Hi I found someone use a class which inherent from iList interface. I don't understand why this person doesn't use a collection in the class instead of inheritance. What is the difference ?
Upvotes: 1
Views: 151
Reputation: 37690
IList defines a contract. The implementor is free to do whatever he wants to respects the contract. The interface does not provide any implementation so the implementor must write the whole behavior
Inheriting an existing collection is a "specialization". That means the inherited class inherits the behavior of the parent, its attributes, etc. The inherited class can then add or override only necessary changes. In most case, the base class provides a set of ready to use methods (it's the case for collection typically).
There is no universal way to choose between the two. In general however, we used to override the base classes instead of implementing the interface. The reason is that the base class contains all the plumbing, the inherited class only add a bit of logic or business methods (FindByName on a CustomerCollection for example). Sometimes you cannot, so you have to move to interface implementation.
Upvotes: 2
Reputation: 64943
That's because this "someone" wanted to implement a kind of list that's not found in the official class library.
In some cases, so concrete requirements will force one to implement an specific type of list by implementing IList or any other (IList, ICollection...) in order to let your own class be compatible with .NET APIs or third-party ones.
Well, at the end of the day, this is the goal of an interface, isn't it? :) A contract!
Upvotes: 3