Why ICollection index does not work when instantiated?

demokritos picture demokritos · Dec 9, 2009 · Viewed 36.8k times · Source

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>();

]

Answer

jeremcc picture jeremcc · Apr 24, 2012

Using LINQ, you can do this:

ProductDTO product = (ProductDTO)Products.ElementAt(0);