Question

i have noticed a very strange behavior in one of the classes in the TFS API that look like breaking the definition of the language.

I tried to imitate it but without success, I have tried to implement collection but not letting whom who use the class to call the indexer setter, as it been done in WorkitemCollection Class. it's important that error will be presented at completion and not at run time,so exception is't valid. WorkitemCollection is implementing an IReadOnlyList which is implementing a Collection. by definition Collection has Index Public Get And Set. yet this code is returning a compile error:

WorkitemCollection wic=GetWorkitemCollection();
wic[0]=null;

why is this happening? thanks in advance.

Was it helpful?

Solution

The solution is explicit interface implementation. This essentially makes that method private when you are working with the class that implements the interface. However, it still can be called by casting the instance of the class to the implementing interface, so you still need to throw an exception.

public class Implementation : IInterface
{
    void IInterface.SomeMethod()
    {
        throw new NotSupportedException();
    }
}

var instance = new Implementation();
instance.SomeMethod(); // Doesn't compile

var interfaceInstance = (IInterface)instance;
interfaceInstance.SomeMethod(); // Compiles and results in the
                                // NotSupportedException being thrown

OTHER TIPS

You can explicitly implement an interface:

int IReadOnlyList.Index
{
    get;
    set;
}

This way you cannot call Index without first casting the object:

((IReadOnlyList)myObj).Index

See C# Interfaces. Implicit implementation versus Explicit implementation

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top