Why ICollection index does not work when instantiated?

Viewed 39389

When we declare a parameter as ICollection and instantiated the object as List, why we can't retrive the indexes? i.e.

ICollection<ProductDTO> Products = new List<ProductDTO>();
Products.Add(new ProductDTO(1,"Pen"));
Products.Add(new ProductDTO(2,"Notebook"));

Then, this will not work:

ProductDTO product = (ProductDTO)Products[0];

What is the bit I am missing?
[Yes, we can use List as declaration an it can work, but I don't want to declare as list, like:

List<ProductDTO> Products = new List<ProductDTO>();

]

7 Answers

Using Linq, you can access an element in an ICollection<> at a specific index like this:

myICollection.AsEnumerable().ElementAt(myIndex);

You can also use extension methods to convert it to (list, array) of ProductDTO

ICollection<ProductDTO> Products = new List<ProductDTO>();
var productsList = Products.ToList();

Then you can use it like that:

productsList[index]
Related