Search code examples
c#interfaceexplicit-interface

Explicit interface implementation cannot be virtual


For the record, I've already seen this connect item but I can't really understand what would be the problem in supporting this.

Say I have the following code:

public interface IInterface
{
    void Method();
}

public class Base : IInterface
{
    virtual void IInterface.Method()
    {
        throw new NotImplementedException();
    }
}

what is the problem with the virtual identifier? Having a virtual modifier would make it possible to override indicating there's a different implementation in the base class. I can make it work now by removing the virtual method and creating the derived class like this:

public class Derived : IInterface
{
    void IInterface.Method()
    {
        throw new NotImplementedException();
    }
}

however this way I've really no indication at all that I'm overriding something.

Update:
According to the C# (part: 20.4.1 Explicit interface member implementations) spec there are 2 reasons.

  1. Hiding of certain methods (which I'm using it for).
  2. Having 2 functions with the same signature but different return types (usefull for IClonable for example).

It doesn't say anything however about why you can't make these methods virtual.

Update2:
Given the answers I think I should rephrase the real question here. If The above 2 reasons are the reason why explicit implementation of interfaces was made possible in the first place. Why would it be a problem if you make a method virtual.


Solution

  • however this way I've really no indication at all that I'm overriding something

    Well, you do, sort of - you have the fact that it's clearly an explicit interface implementation. That shows it's providing polymorphic behaviour for that method call which is specified on an interface... why does it matter whether the base class also implemented the interface? What difference will it make to you when you read the code?

    To me, the main benefit of stating override is to make sure I've really got the right signature - that it matches the thing I'm trying to override. You've already got that benefit with explicit interface implementation, as if you give a non-existent method or the wrong parameters etc, the compiler will already complain.

    I can sort of see your point, but I've never found it to be an actual problem.