CSharp - Explicit interface implementation rules

Introduction

In an explicit interface implementation, the method name is preceded by the interface name, such as <interface name>.methodname (){...}.

Demo

using System;

//Note: Both of the interfaces have the same method name //"Show()".
interface Interface1
{
    void Show();//from   ww  w  . ja  v  a 2 s.  c om
}
interface Interface2
{
    void Show();
}
class MyClass4 : Interface1, Interface2
{
    public void Show()
    {
        Console.WriteLine("MyClass4 .Show() is completed.");
    }

    void Interface1.Show()
    {
        Console.WriteLine("Explicit interface Implementation.Interface1.Show().");
    }

    void Interface2.Show()
    {
        Console.WriteLine("Explicit interface Implementation.Interface2.Show().");
    }
}
class Program
{
    static void Main(string[] args)
    {
        //All the 3 ways of callings are fine.
        MyClass4 myClassOb = new MyClass4();
        myClassOb.Show();

        Interface1 inter4A = myClassOb;
        inter4A.Show();

        Interface2 inter4B = myClassOb;
        inter4B.Show();
    }
}

Result

Rule

In non-explicit implementing interface, we are not using the keyword public. In implicit implementation, it is necessary.

It is a compile-time error for an explicit interface member implementation to include access modifiers, and it is a compile-time error to include the modifiers abstract, virtual, override, or static.

If a class (or struct) implements an interface, then the instance of it implicitly converts to the interface type.

This is why we can use the following lines without any error:

Interface1 inter4A = myClassOb;

Or

Interface2 inter4B = myClassOb;

myClassOb is an instance of the MyClass4 class, which implements both interfaces-Interface1 and Interface2.

Related Topic