.NET Articles

Explicit interface implementation


If interface member is explicitly implemented in a class then same member cannot be accessed from class instance but interface instance. In this article we are going to know about explicit interfaces with examples.

From below example,

interface Inf1
{
    void A();
}

interface Inf2
{
    void A();
    void B();
}

class test : Inf1, Inf2
{
    public void A()
    {
        Console.Write("test.A");
    }
    public void B()
    {
        Console.Write("test.B");            
    }
}

Class “test” implemented 2 interfaces Inf1 and Inf2, Method A() is available in both interfaces. Here code works fine but cannot differentiate from which interface method A() is implemented. If you want to implement method A()for both interfaces then it is possible through explicit interface methods as shown below.

class testExplicitExample1 : Inf1, Inf2
{
    void Inf1.A()
    {
        Console.WriteLine("This is Inf1.A() method.");
    }

    void Inf2.A()
    {
        Console.WriteLine("This is Inf2.A() method.");    
    }

    void Inf2.B()
    {
        Console.WriteLine("This is Inf2.B() method.");        
    }
}

Do not mention access modifier to the explicit interface methods. Then how to call these methods from outside class?

Declare and use interface as shown below.

        
        Inf2 _inf2 = new testExplicitExample1();
        _inf2.A();
        _inf2.B();

Output:

This is Inf2.A() method.
This is Inf2.B() method.

You cannot call explicit interface methods from class variable declaration as shown below.

testExplicitExample1 _testExplicit = new testExplicitExample1();
testExplicit.A() //Incorrect

Explicit interface member hides from calling outside the class (using class instance).

We can create one method as explicit and another one as implicit as shown below.

class testExplicitExample3 : Inf2
{ 
//Implicit
     public void A()
    {
        Console.WriteLine("A()");
    }

//Explicit
    void Inf2.B()
    {
        Console.WriteLine("B()");
    }
}

Many classes implements interface IDisposable, example SqlDataReader class that implements interface IDisposable but you don’t see the interface method Dispose() in SqlDataReader instance this is because of interface explicit implementation as shown below.

class testExplicitExample4 : IDisposable
{

    void IDisposable.Dispose()
    { 
    //Implement your code here
    }
}