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.
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.
With C# 8.0, you can now have default implementations of methods in an interface. Interface members can be private, protected, and static as well. Protected members of an interface cannot be accessed in the class that extends the interface.
An implicit interface implementation is where you have a method with the same signature of the interface. An explicit interface implementation is where you explicitly declare which interface the method belongs to.
A top-level type definition ( interface , class or struct ) can be marked as either public or internal . If no access modifier is given for a top-level type, the default is internal .
A method override in an interface must use the explicit interface implementation syntax. It is an error to declare a class type, struct type, or enum type within the scope of a type parameter that was declared with a variance_annotation. For example, the declaration of C below is an error.
A method implementating interface explicitly has a special visibility scope = you cannot acces it from another method unless you cast "this" to the target interface type. I suppose it was the reason why virtual specifier is not supported - you cannot override method that is not part of the normal object interface (private/protected/public).
This is my workaround:
public class Base : IInterface
{
protected virtual void Method()
{
}
void IInterface.Method()
{
this.Method()
}
}
public class Derived : Base
{
protected override void Method()
{
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With