SyntaxStudy
Sign Up
C# Explicit Interface Implementation
C# Beginner 1 min read

Explicit Interface Implementation

When a class implements two interfaces that declare members with the same name, explicit interface implementation lets you provide separate implementations. An explicitly implemented member is only accessible through a reference of the interface type, not through the class type. This avoids ambiguity and keeps the public API clean. Explicit implementation is also used to hide interface members that are not meaningful for typical users of the class. For example, `List` explicitly implements `IList` (the non-generic version) to avoid cluttering its public API with members that accept `object` arguments. Combining implicit and explicit implementations in one class is valid. The implicit implementation serves as the default when calling through the class type, while the explicit one handles calls through the specific interface reference.
Example
// Explicit interface implementation

public interface IPrinter
{
    void Print(string content);
}

public interface ILogger
{
    void Print(string message); // same name as IPrinter.Print
}

public class Device : IPrinter, ILogger
{
    // Implicit — accessible via Device reference
    public void Print(string content)
        => Console.WriteLine($"[PRINTER] {content}");

    // Explicit — only accessible via ILogger reference
    void ILogger.Print(string message)
        => Console.WriteLine($"[LOG] {message}");
}

var device = new Device();
device.Print("Hello");               // [PRINTER] Hello

IPrinter printer = device;
printer.Print("Document");           // [PRINTER] Document

ILogger logger = device;
logger.Print("Error occurred");      // [LOG] Error occurred

// Practical example: explicit IComparable for custom sort order
public class Employee : IComparable<Employee>, IComparable
{
    public string Name { get; }
    public decimal Salary { get; }

    public Employee(string name, decimal salary) { Name = name; Salary = salary; }

    // Implicit — primary sort: by salary descending
    public int CompareTo(Employee? other) =>
        other is null ? 1 : other.Salary.CompareTo(Salary);

    // Explicit — legacy non-generic interface
    int IComparable.CompareTo(object? obj) =>
        obj is Employee e ? CompareTo(e) : throw new ArgumentException("Not an Employee");
}

var team = new List<Employee>
{
    new("Alice", 80000), new("Bob", 95000), new("Carol", 72000)
};
team.Sort();
team.ForEach(e => Console.WriteLine($"{e.Name}: ${e.Salary}"));