Shieldt describes two reasons for the explicit implementation of interface members, but I don’t understand one of them. Here is what he writes: when the interface method is implemented with its full name, then this method is not available through the class objects that implements this interface, but by the interface reference. Therefore, an explicit implementation allows the interface method to be implemented in such a way that it does not become an open member of the class providing its implementation. I do not understand the meaning of the described and the reason when it should be used and why? The book gives the following example, also I marked the comments that I do not understand also in the code:

interface IEven { bool IsOdd(int x); bool IsEven(int x); } class MyClass : IEven { bool IEven.IsOdd(int x) { if((x%2) != 0) return true; else return false; } // Normal implementation. public bool IsEven(int x) { IEven o = this; //объясните данный участок кода return !o.IsOdd(x); } } class Demo { static void Main() { MyClass ob = new MyClass(); bool result; result = ob.IsEven(4); if(result) Console.WriteLine("4 is even."); // result = ob.IsOdd(4); // Error, IsOdd not exposed. IEven iRef = (IEven) ob; // объясните данный участок кода result = iRef.IsOdd(3); if(result) Console.WriteLine("3 is odd."); } 

    1 answer 1

    In general, this is necessary precisely when a call to the interface method directly at the object is not provided. For example, your internal infrastructure needs this method, and an application programmer who uses your object should not be aware of this.

    The second case is if the interface is not fully implemented. For example, the ControlCollection class implements an IList in which the Insert method is declared, but this method itself does not implement. To prevent the application programmer from tempting to call it, the method is hidden in this way. If you try to call it by NotSupportedException instance of ControlCollection to IList , the method will throw a NotSupportedException .

    Another fairly typical use case for an explicit interface implementation is when a class implements several interfaces whose members conflict by name. For example, all standard collections in .NET implement both ICollection and ICollection<T> . Most of the ICollection members in these classes are implemented explicitly.