0
0
C Sharp (C#)programming~7 mins

Explicit interface implementation in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Explicit interface implementation helps when a class needs to use two interfaces that have methods with the same name. It lets you tell the computer exactly which method belongs to which interface.

When two interfaces have methods with the same name and you want to keep them separate.
When you want to hide an interface method from the class's public methods.
When you want to control how interface methods are accessed through the interface only.
When implementing multiple interfaces that might conflict in method names.
Syntax
C Sharp (C#)
class ClassName : InterfaceName {
    ReturnType InterfaceName.MethodName(Parameters) {
        // method body
    }
}

The method is written with the interface name before the method name.

These methods can only be called through an interface reference, not directly from the class object.

Examples
This class implements two interfaces with the same method name Show. Each method is implemented explicitly to keep them separate.
C Sharp (C#)
interface IFirst {
    void Show();
}

interface ISecond {
    void Show();
}

class MyClass : IFirst, ISecond {
    void IFirst.Show() {
        Console.WriteLine("First Show");
    }
    void ISecond.Show() {
        Console.WriteLine("Second Show");
    }
}
The Display method is implemented explicitly, so it can only be called through an IExample reference.
C Sharp (C#)
interface IExample {
    void Display();
}

class ExampleClass : IExample {
    void IExample.Display() {
        Console.WriteLine("Display from IExample");
    }
}
Sample Program

This program shows a class Speaker implementing two interfaces with the same method Speak explicitly. We call each method through the interface references to get different outputs.

C Sharp (C#)
using System;

interface IAlpha {
    void Speak();
}

interface IBeta {
    void Speak();
}

class Speaker : IAlpha, IBeta {
    void IAlpha.Speak() {
        Console.WriteLine("Alpha speaks");
    }

    void IBeta.Speak() {
        Console.WriteLine("Beta speaks");
    }
}

class Program {
    static void Main() {
        Speaker sp = new Speaker();

        IAlpha alpha = sp;
        IBeta beta = sp;

        alpha.Speak();
        beta.Speak();

        // sp.Speak(); // This would cause a compile error
    }
}
OutputSuccess
Important Notes

You cannot call explicitly implemented methods directly from the class object.

Explicit implementation helps avoid name conflicts in multiple interface inheritance.

Use explicit implementation when you want to hide interface methods from the class's public API.

Summary

Explicit interface implementation separates methods with the same name from different interfaces.

These methods are only accessible through the interface, not the class object.

This technique helps avoid confusion and name conflicts in complex designs.