0

I'm new to C# and OOP, just question on explicit interface implementation. Below is the code:

interface definition:

interface IRun
{
   void Run();  // implicitly public
}

class that implement IRun

class Car: IRun
{
   public void Run()   // have to use public here to match Interface definition
   {
     Console.WriteLine("Run");
   }
}

so we know that the members of an interface never specify an access modifier (as all interface members are implicitly public and abstract), so in the Car class, we can't code like:

class Car: IRun
{
   private void Run()   //compile error, since it is public in interface, we have to math access modifiers
   {
      Console.WriteLine("Run");
   }
}

But I don't understand why if we explicitly implemented interface member as:

class Car: IRun
{
   void IRun.Run()
   {
     Console.WriteLine("Run");
   }
}

and my textbook says explicitly implemented interface members are automatically private.

But isn't that access modifier doesn't match each other(one is public in IRun, the other is private in Car)? how come compiler doesn't throw an error?

P.S I can understand that 'private' access modifier is needed to solve name collision if multiple interfaces have the same method signature. why how come access modifiers can not be the same in original interface definition and implementation?

  • 1
    Possible duplicate of [Why Explicit Implementation of a Interface can not be public?](https://stackoverflow.com/questions/1253266/why-explicit-implementation-of-a-interface-can-not-be-public) – peeyush singh May 27 '19 at 01:10
  • Related: [Why implement interface explicitly?](https://stackoverflow.com/q/4103300/215552) – Heretic Monkey May 27 '19 at 01:13
  • @Heretic Monkey I want to know why compiler doesn't throw an error. –  May 27 '19 at 01:15
  • 1
    ... Because that's how the compiler was programmed. And it was programmed that way because that is what the specification of the language says. That's the least interesting part of the question :). – Heretic Monkey May 27 '19 at 01:18
  • I'm not sure the suggested duplicate really is a duplicate, but it does provide a good insight. Specifically, this quote "You can think of these methods not as being public on the class, but being tied directly to the interface." from the accepted answer. – Zohar Peled May 27 '19 at 06:47

0 Answers0