demokritos
demokritos

Reputation: 1446

Why ICollection index does not work when instantiated?

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

]

Upvotes: 23

Views: 42400

Answers (7)

Qais Bsharat
Qais Bsharat

Reputation: 146

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]

Upvotes: 0

NoRelect
NoRelect

Reputation: 608

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

myICollection.AsEnumerable().ElementAt(myIndex);

Upvotes: 3

jeremcc
jeremcc

Reputation: 8741

Using LINQ, you can do this:

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

Upvotes: 42

Cecil Has a Name
Cecil Has a Name

Reputation: 4992

Then this will work:

ProductDTO product = ((IList<ProductDTO>)Products)[0];

The reason is that the compiler evaluates the lvalue, that is the variable on the left side of '=', to find out which methods and properties it knows it can access at compile-time. This is known as static typing, and ensures that an object member can be accessed directly at runtime by statically knowing that the member is always reachable.

Upvotes: 5

Chris W. Rea
Chris W. Rea

Reputation: 5501

The ICollection interface doesn't declare an indexer, so you can't use indexing to fetch elements through a reference of that type.

You could perhaps try IList, which adds some more functionality, while still being abstract. Of course, this may impact other design decisions so I would look at this carefully.

Upvotes: 29

ChaosPandion
ChaosPandion

Reputation: 78262

ICollection does not define an indexer.

ICollection Non-Generic

ICollection Generic

Upvotes: 7

Stephen M. Redd
Stephen M. Redd

Reputation: 5428

The basic problem is that ICollection doesn't define an index. For the List this is done by the implementation of IList.

Try this:

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

Alternatly, you can keep using ICollection and convert to an array when you need to access the elements by the index:

ICollection<ProductDTO> Products = new List<ProductDTO>();        
ProductDTO z = Products.ToArray()[0];

Upvotes: 3

Related Questions