C#
Beginner
1 min read
Explicit Interface Implementation
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}"));