What is mean by explicit interface implementation?

If a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation.

For Example:

class Test

{

    static void Main()

    {

        SampleClass sc = new SampleClass();

        IControl ctrl = sc;

        ISurface srfc = sc;

        sc.Paint();

        ctrl.Paint();

        srfc.Paint();

    }

}

interface IControl

{

    void Paint();

}

interface ISurface

{

    void Paint();

}

class SampleClass : IControl, ISurface

{

    // Both ISurface.Paint and IControl.Paint call this method.

  public void Paint()

    {

        Console.WriteLine("Paint method in SampleClass");

    }

}

// Output:

// Paint method in SampleClass

// Paint method in SampleClass

// Paint method in SampleClass

But if the two interface members have their own functionality, this can lead to incorrect implementation of one or both of the interfaces. But it is possible to implement the interface members explicitly by using naming the class member with the name of the interface and a period.

public class SampleClass : IControl, ISurface

{

    void IControl.Paint()

    {

        System.Console.WriteLine("IControl.Paint");

    }

    void ISurface.Paint()

    {

        System.Console.WriteLine("ISurface.Paint");

    }

}

The class member IControl.Paint is only available through the IControl interface and surface. Paint is only available through ISurface. Both method implementations are separate, and neither is available directly in the class. 

// Call the Paint methods from Main.

  SampleClass obj = new SampleClass();

//obj.Paint();  // Compiler error.

IControl c = obj;

c.Paint();  // Calls IControl.Paint on SampleClass.

ISurface s = obj;

s.Paint(); // Calls ISurface.Paint on SampleClass.

// Output:

// IControl.Paint

// ISurface.Paint

Post a Comment

0 Comments