1

I'm studying interface and got into something weird interface stuff where the rule is we must implement an interface method public. But not in this example.

I've tried what I learned in my experience and the answer I've found really breaks the rule.

    public interface DropV1
    {
        void Ship();
    }

    public interface DropV2
    {
        void Ship();
    }
    //accepted by the editor
    class DropShipping : DropV1, DropV2
    {
        void DropV1.Ship() { }
        void DropV2.Ship() { }

    }

I was expecting in 1billion percent of the implementation would be:

public void DropV1.Ship()
public void DropV2.Ship()

Why it is like that?

stuartd
  • 70,509
  • 14
  • 132
  • 163
Ronald Abellano
  • 774
  • 10
  • 34
  • 2
    The question would then be this, OK, let me use the class directly: `var ds = new DropShipping(); ds.Ship();` what should now happen? Which of the two methods should this call? – Lasse V. Karlsen Mar 28 '19 at 14:42
  • @LasseVågsætherKarlsen None of the two. Visual Studio intellesense does not show neither of the two methods. – Ronald Abellano Mar 28 '19 at 14:45
  • But of course if the language supported it, Visual Studio should too, I wasn't asking what the current IDE or compiler would do, I was asking what you think it should do. – Lasse V. Karlsen Mar 28 '19 at 14:46
  • @LasseVågsætherKarlsen Okay. I'm going back to the time when I haven't read the answer to my question. I don't really know what would happen because I will get confused about what it will call since they have the same method name in the class. – Ronald Abellano Mar 28 '19 at 14:54
  • 2
    And that's why they couldn't do it like that. You can't have multiple methods with the same signature. The explicit implementation method is the best one as you're allowed to have one public method, and one explicit implementation per interface, as there is no confusion. – Lasse V. Karlsen Mar 28 '19 at 14:59

1 Answers1

6

It is not a private it is called explicit interface implementation. Within an interface all methods are public by definition so you don't need public keyword(even if you want you cannot use it here). The important to mention is that when explicitly implemented an interface methods are available only through an interface instance but not the class instance:

public class SampleClass : IControl
{
    void IControl.Paint()
    {
        System.Console.WriteLine("IControl.Paint");
    }
}

IControl ctrl = new SampleClass();
ctrl.Paint(); //possible

SampleClass ctrl = new SampleClass();
ctrl.Paint(); //not possible

var ctrl = new SampleClass();
ctrl.Paint(); //not possible

((IControl) new SampleClass()).Paint(); //possible
Johnny
  • 8,939
  • 2
  • 28
  • 33