Search code examples
c#collectionbase

I receive the following error while trying to get the index of a class that inherits from CollectionBase: Cannot apply indexing with []


I have a class that inherits from CollectionBase.

public NavigationMenuItemsCollection MenuItems { get; set; }

I have a method that is attempting to get the item from the index, but it's not working.

public void ActivatePage(int index)
{
   NavigationMenuItem navigationMenuItem = (NavigationMenuItem)MenuItems[0];
}

enter image description here

CollectionBase inherits from IList, ICollection, and IEnumerable. So I thought it could be indexed. Any ideas on what's going on?


Solution

  • CollectionBase implements IList's indexer property with an explicit interface implementation, meaning that you'd normally have to cast the collection as an IList in order to have access to it.

    NavigationMenuItem navigationMenuItem = (NavigationMenuItem)((IList)MenuItems)[0];
    

    If you are able to modify the source code of NavigationMenuItemsCollection, you should be able to add an indexer to it yourself, as shown in the first example here.

    public class NavigationMenuItemCollection : CollectionBase  {
    
       public NavigationMenuItem this[ int index ]  {
          get  {
             return( (NavigationMenuItem) List[index] );
          }
          set  {
             List[index] = value;
          }
       }
       ...