If a class implements two interfaces that have members with the same signature it is possible to end up calling the wrong method while using the class. In order to avoid these kinds of problems you can choose to implement the interface explicitly, that is, the interface name itself is used to differentiate between conflicting interface signatures.

Unfortunately explicit interfaces cannot be called from a this operator, which means that you have to jump through a few simple hoops in order access member variables that were associated with interface. In the following code snippet I show three ways that you can get at your explicit method from within the class. You can use the Cast operator, As operator or an implicit conversion.

interface ILamp
{
    string Switch();
}

public class BigLamp : ILamp
{
    string ILamp.Switch()
    {
        return "Your Explicit Interface!";
    }
    
    public string Method1()
    {
        ILamp lmp = (ILamp)this; //Cast
        return lmp.Switch();
    }

    public string Method2()
    {
        return (this as ILamp).Switch(); //As operation
    }

    public string Method3()
    {
        ILamp ia = this; //Implicit conversion
        return ia.Switch();
    }
}

As a word of warning if you are designing an API my advice is to remain consistent with whatever approach you select. For example using a cast operation will throw an exception if it is unable to convert the type, in contrast the As operator will return null and so any assignments from this operation will need to be nullable. The cast operation communicates a guarantee in the validity of the conversion, the as operator implies a lack of certainty. Choose wisely!



Comment Section

Comments are closed.