C# interface method ambiguity

Implement explicitly:

public class AllYourBase : IBase1, IBase2
{
    int IBase1.Percentage { get{ return 12; } }
    int IBase2.Percentage { get{ return 34; } }
}

If you do this, you can of course treat your non-ambigous properties just like normal.

IAllYourBase ab = new AllYourBase();
ab.SomeValue = 1234;

However, if you want to access the percentage prop this will not work (Suppose it did, which value would be expected in return?)

int percent = ab.Percentage; // Will not work.

you need to specify which percentage to return. And this is done by casting to the correct interface:

int b1Percent = ((IBase1)ab).Percentage;

As you say, you can redefine the properties in the interface:

interface IAllYourBase : IBase1, IBase2
{
    int B1Percentage{ get; }
    int B2Percentage{ get; }
}

class AllYourBase : IAllYourBase 
{
   public int B1Percentage{ get{ return 12; } }
   public int B2Percentage{ get{ return 34; } }
   IBase1.Percentage { get { return B1Percentage; } }
   IBase2.Percentage { get { return B2Percentage; } }
}

Now you have resolved the ambiguity by distinct names instead.

Leave a Comment