Why does C# not support explicit abstract interface implementations?

M

Marcel Müller

The following code is not valid - why?

interface ITest
{ string Get();
}

abstract class ATest : ITest
{ abstract string ITest.Get(); // Invalid
}

class Test : ATest
{ string ITest.Get()
{ return "Buh!";
}
}

The usual work around is

abstract class ATest : ITest
{ protected abstract string Get();
string ITest.Get()
{ return Foo();
}
}

class Test : ATest
{ protected override string Get()
{ return "Buh!";
}
}

Unfortunately this has the following drawbacks:
- The implementation is no longer explicit. It must be at least protected.
- You have to work around for name clashes manually, e.g if the class
has itself a Get method with another signature or if two implemented
interfaces have a method with the same name but different signature or
semantic.
- Calling ITest.Foo() causes a second vtable lookup. This creates a
completely unnecessary runtime overhead. I am unsure whether the JIT can
compensate for that.


Another work around is to throw an exception in the abstract base class
nut never execute this code:

abstract class ATest : ITest
{ string ITest.Get()
{ throw NotImplementedException();
}
}

class Test : ATest, ITest
{ string ITest.Get()
{ return "Buh!";
}
}

But this has some other serious drawbacks.
- The compiler can no longer detect if class Test implements the
interface completely.
- The derived class Test must repeat all explicit interface
implementations of ITest not only the (logically) abstract ones.


Marcel
 
M

Marcel Müller

Peter said:
Explicit implementations are private. You can't override private
members, but an abstract member must be overridden at some point.

Well, that's somehow a point of view question. I never intended to
/override/ an interface implementation, since there is nothing to
override so far.

But you are right, abstract functions operate in the same way. You must
override them to implement them. I always found this little intuitive,
since from the technical point of view implementing an interface
function and implementing an abstract function is the same.
The two are simply mutually exclusive. It would not make any sense to
allow private abstract members of any kind, and that includes explicit
interface implementations.

Other languages have no problems with that.


Marcel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top