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
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