Tono Nam
Tono Nam

Reputation: 36048

Class does not implement Interface and code still compiles

I need to create a custom collection that implements IBindingList in order to be able to bind it with a custom control from 3rd party. Another problem that I have is that I have to make that collection thread safe because I manually insert items from multiple threads simultaneously.

Anyways I am using a BindingList<T> as a field on my class in order to don't reinvent the wheel to much. So my class looks like:

class ThreadSaveBindingCollection<T> : IEnumerable<T>, IBindingList
{
    BindingList<T> collection;
    object _lock = new object();

    // constructors
    public ThreadSaveBindingCollection(IEnumerable<T> initialCollection)
    {
        if (initialCollection == null)
            collection = new BindingList<T>();
        else                            
            collection = new BindingList<T>(new List<T>(initialCollection));                                 
    }
    public ThreadSaveBindingCollection() : this(null)
    {            
    }   

    // Todo: Implement interfaces using collection to do the work    
}

Note I am missing to implement the interface IEnumerable and IBinding list. I am planning for the field collection to take care of that as it implements those interfaces as well. So I let visual studio implement the interface explicitly and replace the throw new NotImplementedException() with the field collection implementation and I end up with something like:

enter image description here

Now the question is

Why I cannot call the method AddIndex on the field collection if collection claims to implement IBindingList!?

enter image description here

I am not able to do the same thing for several of the methods

Upvotes: 0

Views: 641

Answers (3)

Tyler Lee
Tyler Lee

Reputation: 2785

BindingList explicitly implements IBindingList, so you need to do

(collection as IBindingList).AddIndex(property);

Upvotes: 1

Kent Boogaart
Kent Boogaart

Reputation: 178650

It's because it's an explicit implementation of the interface, rather than implicit. This means you must call it through the interface rather than the type itself. For example:

((IBindingList)collection).AddIndex(property);

See here for more information on explicit interface implementations.

Upvotes: 1

Adam Houldsworth
Adam Houldsworth

Reputation: 64477

It is implemented explicity by BindingList, you need to cast your reference of collection to IBindingList to use it:

(collection as IBindingList).AddIndex(property);

http://msdn.microsoft.com/en-us/library/ms132679.aspx

Further reading.

The point of explicit implementation and access via a reference of the interface itself is to resolve naming conflicts where two parties create two separate interfaces with the same method signatures - it allows you to disambiguate the methods whilst still implementing both interfaces.

Upvotes: 1

Related Questions