1

I've tried to create a simple class implementing IList. However the members are not available unless I first cast DiskBackedCollection to IList. How can I make it usable without casting?

public partial class DiskBackedCollection<T> : IList<T>
{
    private List<T> _underlyingList = new List<T>();

    int IList<T>.IndexOf(T item)
    {
        return _underlyingList.IndexOf(item);
    }

    T IList<T>.this[int index]
    {
        get
        {
            return _underlyingList[index];
            throw new NotImplementedException();
        }
        set
        {
            throw new NotImplementedException();
        }
    }

    int ICollection<T>.Count
    {
        get
        {
            return _underlyingList.Count;
        }
    }

    IEnumerator<T> IEnumerable<T>.GetEnumerator()
    {
        return new DiskBackedCollectionEnumerator(this);
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return new DiskBackedCollectionEnumerator(this);
    }
}
Lee
  • 1,591
  • 1
  • 14
  • 28
  • 3
    [C# Interfaces. Implicit implementation versus Explicit implementation](http://stackoverflow.com/questions/143405/c-sharp-interfaces-implicit-implementation-versus-explicit-implementation). – poke May 25 '13 at 13:50
  • And I managed to get into my head it was just a code clarity thing! - Thanks for the link. – Lee May 25 '13 at 13:52
  • Not relevant to your question, but it will usually simplify your code to use the base class `Collection`, which has virtual methods `InsertItem`, `RemoveItem` etc that you can override for any custom functionality. – Joe May 25 '13 at 15:24
  • @Joe To my knowledge the Collection class uses an internal List to store the items. So the class is best used for adding validation to a simple list. However as I'm going to be storing and retrieving the data from disk (many millions of rows), I don't want it to be stored in a list internally. From my implementation above you are correct, but it is far from complete. – Lee May 26 '13 at 12:15
  • @Lee, you're right, except that to be pedantic, it uses an internal `IList`, which doesn't have to be a `List`. My comment was based on your implementation above (_underlyingList). – Joe May 26 '13 at 16:19

2 Answers2

2

It's because each of the members has IList<T>. in front of them. Remove that and they should show up.

Implementating the interface members with an IList<T>. in front of them is called explicit implementation.

Zach Johnson
  • 23,678
  • 6
  • 69
  • 86
  • @DaveShaw The compiler should complain if you don’t publicly implement an interface (in which case you technically wouldn’t have implemented it). – poke May 25 '13 at 13:53
0

Your methods that implement interface requirements must be public. Yours are not.

Also, you need to remove your explicit implementation:

public int Count
{
  get
  {
    return _underlyingList.Count;
  }
}
Matt Houser
  • 33,983
  • 6
  • 70
  • 88