Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving ambiguity in an interface which extends two other interfaces which have a method with the same name

Tags:

c#

interface

if I have interfaces:

public interface ANewThing { IKey Key { get; } }

public interface AnOldThing { object Key{ get; } }

public interface ACompositeThing : ANewThing , AnOldThing  { }

and I write this:

ACompositeThing compositeThing = GetCompositeThing();  
Trace.WriteLine(compositeThing.Key);

it doesn't compile, complaining that the call to Key is ambiguous (it doesn't make any difference if the type returned by the Key property is the same). I am aware that in the class implementing ACompositeThing I can explicitly implement the interfaces ANewThing and AnOldThing, but this doesn't help me when I have methods which don't know about the concrete implementations and only know that they will be given ACompositeThing.

So my question is:

Can I do anything in the ACompositeThing interface to say how the Key property ambiguity should be resolved?

Like say 'when accessing the Key property through this interface, always return the Key property from the ANewThing implementation'?

Or do I have to accept that I can't do this and must always cast my ACompositeThing to one of the other interfaces before I do the access?

like image 629
Sam Holder Avatar asked Oct 20 '25 20:10

Sam Holder


1 Answers

It's nasty, but you can declare another member in ACompositeThing:

public interface ACompositeThing : ANewThing , AnOldThing {
    new IKey Key { get; }
}

Now that will take preference from the caller's point of view. However, it means there are now potentially three different implementations - and any ACompositeThing implementation which uses explicit interface implementation for ANewThing.Key will either have to change to expose the member publicly, or add a new member to implement ACompositeThing.Key.

Of course if you possibly can, you should avoid this - or only use it in a transition from an old interface to a new interface for a very limited time.

like image 93
Jon Skeet Avatar answered Oct 22 '25 09:10

Jon Skeet