1. Introduction
Usually, when you implement an interface, you just create public methods in your class whose signatures match those declared in the interface. This is called implicit or public implementation. The compiler is smart enough to figure out: "Aha, this DoSomething() method in MyClass is meant to implement IDoable.DoSomething()!"
But what if:
- Your SmartDevice class implements the ICamera interface (which has a TakePicture() method) and the IScreen interface (which also has a TakePicture() method—for taking a screenshot)?
- Or your Robot class already has a public Reset() method for a full system reset, but you also want it to implement the IDevice interface with a Reset() method that should only reset some settings?
In these cases, you get ambiguity or you want to clearly separate functionality. That's where explicit interface implementation comes in.
Explicit interface implementation lets you tell the compiler: "This specific method is for implementing this exact interface, and it'll be available only through a reference to that interface." It's like Peter Parker shooting webs only when he's acting as Spider-Man, and using his photography skills when he's just "regular" Peter Parker.
2. When and Why You Need Explicit Interface Implementation
When you implement an interface the usual way, its methods and properties become part of your class's public interface. But sometimes you want them to be available only through the interface itself, not directly through the class. This happens more often than you think! For example, if two interfaces require the same method (but with different meanings), or you want to restrict access to the implementation only for users working with the object strictly through the interface.
That's where explicit interface implementation comes to the rescue. It's like a secret passage in your code architecture: you can't see it from the outside, but those in the know can get through!
Scenario 1: Name Conflict
Imagine you have a class that implements two interfaces, and both require a method with the same name but totally different logic. For example:
interface IWriter
{
void Print();
}
interface IPrinter
{
void Print();
}
You want IWriter.Print() to write text to a file, and IPrinter.Print() to send it to a printer. A regular implementation of a Print() method won't let you separate the behaviors. That's where explicit implementation saves the day.
Scenario 2: Hiding Irrelevant/Technical Interface Methods
Sometimes your class has to implement an interface method, but you really don't want to offer it to all consumers of your class (for example, the interface member is only needed for internal infrastructure work).
Scenario 3: Protecting from Accidental Calls
If an interface method isn't meant to be called directly (like an internal framework mechanism), you can implement it explicitly—then a random programmer can't call it directly through the class object.
3. Syntax of Explicit Interface Implementation
The main difference—with explicit implementation, you name methods and properties with the full interface qualifier. And no access modifiers (public/private) or the override keyword!
General syntax:
ReturnType InterfaceName.MethodName(parameters)
{
// implementation
}
It looks like you're explicitly specifying the interface name so the compiler and your teammates don't get confused about which contract this implementation belongs to.
Resolving Name Conflicts
Let's look at that case with IWriter and IPrinter. We're building our learning app, and let's say we have a report class:
interface IWriter
{
void Print();
}
interface IPrinter
{
void Print();
}
public class Report : IWriter, IPrinter
{
// Explicit implementation of IWriter.Print
void IWriter.Print()
{
Console.WriteLine("Saving report to file (Writer)...");
}
// Explicit implementation of IPrinter.Print
void IPrinter.Print()
{
Console.WriteLine("Sending report to paper printer (Printer)...");
}
// Extra method for user output
public void Show()
{
Console.WriteLine("Displaying report on screen.");
}
}
Now let's try using the different interfaces:
var report = new Report();
report.Show(); // Regular public method
// report.Print(); // Error! No Print method with that name in Report
IWriter writer = report;
writer.Print(); // Calls IWriter.Print() implementation
IPrinter printer = report;
printer.Print(); // Calls IPrinter.Print() implementation
Here, the Print methods aren't available through the report object itself, but are available through the right interface. That's the core of explicit implementation: you only get to the method through the interface "port."
How It Looks in Memory: Simple Illustration
Basically, explicit implementation "hides" the interface member inside the class. To visualize, you can imagine a table like this:
| How you call it | What actually gets called |
|---|---|
|
Compile error—no such method |
|
Explicit implementation |
|
Explicit implementation |
|
Show method of the class |
4. Example: Interface—Only for Infrastructure
In real projects, you often see this scenario: a class has to implement some service interface, but the implementation isn't needed by regular users of the class.
interface IBroadcastable
{
void Broadcast();
}
public class SecretMessage : IBroadcastable
{
void IBroadcastable.Broadcast()
{
Console.WriteLine("Secret message sent to the air...");
}
public void Reveal()
{
Console.WriteLine("Showing secret on screen.");
}
}
// In regular code:
var message = new SecretMessage();
message.Reveal(); // User method
// message.Broadcast(); // Error! — no such method
// Only infrastructure knows what to do:
((IBroadcastable)message).Broadcast();
Here, the Broadcast() method is only for those working by the interface contract.
5. Explicit Implementation of Properties and Indexers
You can explicitly implement not just methods, but also properties and even indexers.
interface IDescribable
{
string Description { get; }
}
public class Product : IDescribable
{
// Explicit implementation of property
string IDescribable.Description => "Description available only through the interface";
// Regular public property
public string Name { get; set; }
}
// Usage example:
var p = new Product { Name = "Gadget" };
// p.Description; // Error! No such property in Product
var descr = ((IDescribable)p).Description;
Console.WriteLine(descr);
6. Useful Nuances
How Inheritance Works with Explicit Implementation
With inheritance, everything works intuitively: if the base class implements an interface explicitly, the derived class inherits that "behavior." But if the derived class wants to override the interface method implementation, it can't: explicit implementation can't be virtual. So, you can't override an explicitly implemented member.
If you need that behavior—you'll have to use a regular implementation or consider the "template method" pattern.
Explicit and Implicit Implementation
+----------------+
| Invoice |
+----------------+
| Show() | // Can be called directly
+----------------+
| ITxtExportable.Export() // Only through ITxtExportable
| IJsonExportable.Export() // Only through IJsonExportable
+----------------+
Features/Limitations of Explicit Implementation
- Explicitly implemented methods and properties can't have access modifiers. They're private to the outside world by default and only accessible through the interface.
- You can't make such members static, virtual, abstract, or override.
- You can't access an explicitly implemented member directly through the class object (only through a variable of the interface type).
- If an interface inherits another interface, you can explicitly implement members at any level of the hierarchy.
7. Advantages of Explicit Implementation
Explicit implementation isn't just a syntax trick for resolving collisions. There are several solid reasons for it:
Resolving name collisions (The Big One): This is the main and most obvious reason. If two interfaces you implement declare methods (or properties) with the same signatures, explicit implementation lets you provide separate, interface-specific implementations. Without it, you'd have ambiguity.
Real-world example: Imagine you have a printer. It can also be a scanner. The IPrinter interface has a Print() method, and the IScanner interface has a Scan() method. But what if both interfaces had a ProcessDocument() method? Explicit implementation lets you make IPrinter.ProcessDocument() for printing and IScanner.ProcessDocument() for scanning, and they'll work differently.
Hiding implementation details and keeping the class API clean: Explicitly implemented methods aren't part of your class's public API. They're only available when you cast the object to the interface type. This is super useful when you want certain functionality to be available only "by contract," not as part of your object's general behavior.
Example: You're building a complex financial tool, like a CreditCard. It might implement IPayable (for making payments) and IAdminConfigurable (for internal settings, like setting limits). The IAdminConfigurable.SetLimit() method shouldn't be available to everyone holding a CreditCard. It should only be available to the admin system working with CreditCard as an IAdminConfigurable. Explicit implementation keeps SetLimit() hidden from general access to CreditCard, making the class API cleaner and safer.
Contract guarantee: Sometimes a method in your class by accident has the same signature as a method in an interface, but you don't want it to count as the implementation. For example, you have a MyList class with a Clear() method for clearing its internal state. If you decide MyList should implement IList<T>, which also has Clear(), by default your MyList.Clear() becomes the implementation of IList<T>.Clear(). If their logic should be different, explicit implementation of IList<T>.Clear() lets you separate them.
Implicit vs. Explicit Implementation
To really see the difference, let's look at a quick comparison table:
| Characteristic | Implicit Implementation | Explicit Implementation |
|---|---|---|
| Availability | Available through both the class and the interface. | Available only through the interface. |
| Access modifier | Usually public (or protected, etc.). | No access modifier (can't be public). |
| Syntax | |
|
| Collision resolution | Doesn't resolve; method serves all interfaces with that signature. | Resolves collisions, allowing different implementations. |
| Class API cleanliness | Method is part of the class's public API. | Method isn't part of the class's public API. |
| Purpose | For general, unambiguous interface implementations. | For resolving collisions or hiding specific logic. |
As you can see, they're two sides of the same coin, and each has its own purpose. Most of the time you'll use implicit implementation because it's easier and more convenient. Explicit implementation is a tool for specific but important tasks.
8. Common Mistakes with Explicit Interface Implementation
Mistake #1: Method not visible through the class object.
Explicitly implemented methods aren't available directly through the class instance. This often causes confusion: the compiler says the method isn't found, even though it exists—it's just "hidden." Solution: cast the object to the interface type, like (IMyInterface)obj.Method().
Mistake #2: Incorrect use of access modifiers.
With explicit implementation, you can't specify modifiers like public or override. Trying to do so will cause a compile error—the compiler won't accept such declarations.
Mistake #3: Trying to override an explicitly implemented method in a derived class.
If an interface method is explicitly implemented in a base class, you can't override it in a subclass. You need to keep this limitation in mind when designing class hierarchies with interfaces.
GO TO FULL VERSION