Explicit Interface Implementation

Internal Interface Classes in C# | Alex Franchuk Interfaces can be explicitly implemented. Assume a case where a class implements two interfaces that have a member with the same signature:

public interface IControl { void Paint(); }
public interface ISurface { void Paint(); }

public class SampleClass : IControl, ISurface 
{
    public void Paint();
}

SampleClass sample = new SampleClass();
IControl control = sample;
ISurface surface = sample;

These all call the same method:

sample.Paint();
control.Paint();
surface.Paint();

To call a different implementation depending on which interface is in use, implement an interface member explicitly:

public class SampleClass : IControl, ISurface 
{
    void IControl.Paint() { // …implementation… }
    void ISurface.Paint() { // …implementation… }
}

SampleClass sample = new SampleClass();
IControl control = sample;
ISurface surface = sample;

Now:

sample.Paint(); // This call fails.
control.Paint();
surface.Paint();

Explicit Interface Member Implementation

interface IDimensions 
{
    float GetLength();
    float GetWidth();
}

class Box : IDimensions 
{
    float lengthInches;
    float widthInches;

    Box(float length, float width) 
    {
        lengthInches = length;
        widthInches = width;
    }

    // Explicit interface member implementation:
    float IDimensions.GetLength() { return lengthInches; }
    float IDimensions.GetWidth() { return widthInches; }
}