Reputation: 3573
Can anyone explains me why to not inherit from IList? I saw many inputs here that it's better to inherit from Collection if i need to provide custom collection class for my object and not from IList. Why is that? Why people saying not inherit from IList? If possible please make an example.
i see its possible to like this so why not use it as List provide more features:
class FootballTeam : List<FootballPlayer>
{
}
Upvotes: 3
Views: 3426
Reputation: 8273
This doesn't provide direct answer, might have overview
IList provides you the flexibility of implement this functionality.
public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable
{
T this[int index] { get; set; }
int IndexOf(T item);
void Insert(int index, T item);
void RemoveAt(int index);
}
if you use
class FootballTeam : List<FootballPlayer>
you can extent the properties in your FootballTeam class.
Ideally it will be necessary when you want to extend your collection. Suppose you have to implement AddSort(T item) then class FootballTeam : List<FootballPlayer>
if you use
class FootballTeam : ILIst<FootballPlayer>
you might be reinventing the wheel thatAdd()
, andContains()
should be implemented by yourself
I would recommend to use Composition over inheritance
class FootballTeam : //So here can use any team base class or anything necessary
{
public string TeamName;
public int RunningTotal
private List<FootballPlayer> _players
public IEnumerable<FootballPlayer> Players {get;set;}
}
Update
I have updated the Players
as IEnumerable so will have much flexibility.
illustration and Credits from this link: When To Use IEnumerable, ICollection, IList And List
Upvotes: 6
Reputation: 120
If you are going to customize either List or Collection interface which its concrete implementation List or Collection does not provide then do implement the IList or ICollection inteface , other wise to use any list or collection "Composition is better than inheritence".
Upvotes: -1
Reputation: 44298
better not to do it all and model it like
class FootballTeam
{
public string TeamName;
public int RunningTotal
public IList<FootballPlayer> Players
}
you'd normally inherit off a collection if you wanted to implement a new kind of collection like a DiskCachedCollection or something
This is known as "Composition over Inheritance" https://en.wikipedia.org/wiki/Composition_over_inheritance
It becomes obvious why when a new requirement comes a long.... "We want to track the management staff against a team". Suddenly you go hmmm, how can a team be a collection of players and a collection of management. Oh! it's not, a team is composed of players and management
Upvotes: 3