Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does List<T> implement so many interfaces? [duplicate]

List<T> derives from the following interfaces:

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable

I just wonder, why it needs all these interfaces (in the class declaration)?

IList itself already derives from ICollection<T>, IEnumerable<T> und IEnumerable.

So why is the following not enough?

public class List<T> : IList<T>, IList

I hope you can solve my confusion.

like image 510
Andy Avatar asked Dec 06 '13 12:12

Andy


2 Answers

Indeed List<T> would have just implemented like this

public class List<T> : IList<T>, IList

It is the reflector or such decompiler shows you all the interfaces in inheritance.

Try this

public class List2<T> : IList<T>

I just compiled this and viewed in reflector, which shows like this

public class List2<T> : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable
like image 87
Sriram Sakthivel Avatar answered Oct 20 '22 10:10

Sriram Sakthivel


If you take a peek into actual .NET source code you'll see that it does not redundantly mention all the interfaces:

// Implements a variable-size List that uses an array of objects to store the
// elements. A List has a capacity, which is the allocated length 
// of the internal array. As elements are added to a List, the capacity
// of the List is automatically increased as required by reallocating the
// internal array.
// 
[DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")] 
[Serializable] 
public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T>

The reflector just lists all the interfaces.

You can get the source code of .NET here, or do a quick search here (seems to stuck at .NET4).

like image 39
gwiazdorrr Avatar answered Oct 20 '22 09:10

gwiazdorrr