Explicit Interface Implementation in C#: What It Is and How It Works
explicit interface implementation is a way to implement interface members so they are only accessible through the interface, not the class instance directly. This helps avoid naming conflicts and controls how interface methods are accessed.How It Works
Explicit interface implementation means you write the interface method with the interface name before it, like InterfaceName.MethodName. This hides the method from the class's normal methods, so you can only call it when you use the object as the interface type.
Think of it like having a secret door that only opens if you have the right key (the interface). If you try to open it directly from the house (the class), it won’t work. This is useful when two interfaces have methods with the same name, and you want to keep them separate.
Example
This example shows a class implementing two interfaces with the same method name using explicit interface implementation. You can only call the methods through the interface, not directly from the class.
using System;
interface IFirst
{
void Show();
}
interface ISecond
{
void Show();
}
class MyClass : IFirst, ISecond
{
void IFirst.Show()
{
Console.WriteLine("IFirst Show method called");
}
void ISecond.Show()
{
Console.WriteLine("ISecond Show method called");
}
public void Show()
{
Console.WriteLine("MyClass Show method called");
}
}
class Program
{
static void Main()
{
MyClass obj = new MyClass();
obj.Show(); // Calls class method
IFirst first = obj;
first.Show(); // Calls IFirst method
ISecond second = obj;
second.Show(); // Calls ISecond method
}
}When to Use
Use explicit interface implementation when you want to avoid method name conflicts from multiple interfaces or when you want to hide interface methods from the class's public API. This is common in large projects where different interfaces might have methods with the same name but different meanings.
It also helps when you want to force users of your class to access certain methods only through the interface, keeping your class interface clean and clear.
Key Points
- Explicit interface methods are only accessible via the interface type, not the class instance.
- It helps resolve naming conflicts when multiple interfaces have the same method names.
- Explicit implementation hides interface methods from the class's public API.
- Useful for controlling how methods are accessed and keeping class interfaces clean.