What are the advantages of explicit interface implementation in C#?

638 views Asked by At

C# supports built-in mechanism for differentiating methods that have the same names. Here is a simple example below shows how it works:

interface IVehicle{
    //identify vehicle by model, make, year
    void IdentifySelf();    
}

interface IRobot{
    //identify robot by name
    void IdentifySelf();
}

class TransformingRobot : IRobot, IVehicle{ 
    void IRobot.IdentifySelf(){
        Console.WriteLine("Robot");
    }

    void IVehicle.IdentifySelf(){
       Console.WriteLine("Vehicle");
    }
}

What are the use cases or benefits of this distinction? Do I really need to differentiate abstract methods in implementing classes?

1

There are 1 answers

0
David Arno On BEST ANSWER

In your case, there's no real benefit, in fact having two methods like that is just confusing to the user. However, they are key when you have:

interface IVehicle
{
    CarDetails IdentifySelf();    
}

interface IRobot
{
    string IdentifySelf();
}

Now we have two methods of the same name, but different return types. So they cannot be overloaded (return types are ignored for overloading), but they can be explicitly referenced:

class TransformingRobot : IRobot, IVehicle
{
    string IRobot.IdentifySelf()
    {
        return "Robot";
    }

    CarDetails IVehicle.IdentifySelf()
    {
        return new CarDetails("Vehicle");
    }
}