0

I was always using interfgaces similarly to abstract classes - just to make sure all objects will have consistent external methods etc.

But from MSDN, I do not get that:

interface ISampleInterface
{
    void SampleMethod();
}

class ImplementationClass : ISampleInterface
{
    // Explicit interface member implementation:  
    void ISampleInterface.SampleMethod()
    {
        // Method implementation.
    }

    static void Main()
    {
        // Declare an interface instance.
        ISampleInterface obj = new ImplementationClass();

        // Call the member.
        obj.SampleMethod();
    }
}

Why there is explicitly mentioned interface name in the method declaration and why it does not work without it? Also why is the interface being instantionated, shouldn't be just instance of class implementing it?

John V
  • 4,855
  • 15
  • 39
  • 63

1 Answers1

1

Why there is explicitly mentioned interface name in the method declaration and why it does not work without it?

Sometimes it is handy to make your interface explicitly implemented. See this other Stack Overflow questions answer: https://stackoverflow.com/questions/408415/why-explicit-interface-implementation

Also why is the interface being instantionated, shouldn't be just instance of class implementing it?

They instanciate the ImplementationClass but downcast it to the ISampleInterface Thus preventing themselves from touching non-interface contract guaranteed methods/properties.

Mark van Straten
  • 9,287
  • 3
  • 38
  • 57
  • Thanks! I just wonder how come it does not work if I change the explicit to implicit and instantionate class instead of the interface. – John V Jan 06 '14 at 11:06
  • @user970696: It _should_ work fine implicitly without downcasting to the interface. Perhaps you can post your usage code in another question? – Chris Sinclair Jan 06 '14 at 11:08
  • I just removed the ISampleInterface from the method declaration and I am getting a message that this class does not implement the SampleMethod. – John V Jan 06 '14 at 11:15