Romil Kumar Jain
Romil Kumar Jain

Reputation: 20745

Why .Net FCL is implementing generic and non-generic interface IList and IList<T> in List<T> class at same time?

The List is implemented in following manner in .NET I am surprised why they have implemented generic and non-generic interface in class at same time.

[Serializable]
public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>,
IList, ICollection, IEnumerable {
public List();
public void Add(T item);
public Int32 BinarySearch(T item);
public void Clear();
public Boolean Contains(T item);
public Int32 IndexOf(T item);
public Boolean Remove(T item);
public void Sort();
public void Sort(IComparer<T> comparer);
public void Sort(Comparison<T> comparison);
public T[] ToArray();
public Int32 Count { get; }
public T this[Int32 index] { get; set; }
}

Upvotes: 3

Views: 185

Answers (2)

Hans Passant
Hans Passant

Reputation: 941625

Microsoft made it very easy to help .NET programmers forget that COM exists. This is however not close to reality, COM is alive and well and is still the primary interop technology on Windows. Just as a recent example, Modern UI in Store and Phone apps are purely COM based under the hood. Very carefully hidden though, there is practically no way to tell that you are actually using COM when you write a C# app. Other than the seemingly black magic of effortlessly working with code written in Javascript or C++.

Generics in .NET are an interop problem, it is a pure .NET implementation detail that other non-.NET languages know absolutely nothing about. So List<T> cannot be [ComVisible(true)].

IList, ICollection and IEnumerable to the rescue, interfaces that are ComVisible and usable by code written in practically any language on Windows.

Upvotes: 3

Dennis
Dennis

Reputation: 37770

It's a compatibility issue. There are many components (e.g., in UI libraries), which use non-generic IList, because usage of generic version isn't necessary and often not desirable here.

Consider this WPF sample:

var list = new List<MyDataType>();
var collectionView = new ListCollectionView(list);

Suppose, that List<T> doesn't implement IList - you just couldn't use it in this sample. Moreover, imagine, that ListCollectionView must be generic, and try to implement it.

Upvotes: 1

Related Questions