What is the purpose of implementing the IList
interface in a generic List<T>
collection?
What is the interface method Add(object? item)
for in List<T>
?
Why is this code useful?
List<int> list= new List<int>();
((IList)list).Add(1);
Your code, as shown, is not very useful. It is not useful to make a generic List<T>
, and only to then cast to a non-generic IList
, throwing away the type safety.
One important reason for the generic collection types to still implement the non-generic collection interfaces is for backwards-compatibility.
This is useful if you are calling some code code written before C# 2, where there were no generic collections (or rather, no generics at all). That code could not have been written using the generic collection interfaces, and could only take e.g. the non-generic IList
.
Let's say in your new code, you have a generic List<string>
that you want to pass to the old code, and you know that the old code does not add some other type of elements to the list. In this case, being able to "just" pass the list directly (because List<T>
implements IList
), is very convenient. Otherwise, you would have to create an instance of the old ArrayList
class and copy the elements over.
That said, I don't know how often one would need something from as far back as before C# 2, so I don't know how useful this is in practice. In any case, the C# language team really hates breaking old code.