I can't do this
interface InterfaceA
{
void MethodA();
}
class ClassA : InterfaceA
{
virtual void InterfaceA.MethodA()
// Error: The modifier 'virtual' is not valid for this item
{
}
}
Where the following works
class ClassA : InterfaceA
{
public virtual void MethodA()
{
}
}
Why? How to circumvent this?
Yes, you can have virtual interface members in C# 8. Any interface member whose declaration includes a body is a virtual member unless the sealed or private modifier is used. So by default, all the default interface methods are virtual unless the sealed or private modifier is used.
C# methods in interfaces are declared without using the virtual keyword, and overridden in the derived class without using the override keyword.
An implementing class is free to mark any or all of the methods that implement the interface as virtual. Derived classes can override or provide new implementations. For example, a Document class might implement the IStorable interface and mark the Read( ) and Write( ) methods as virtual .
Access modifiers such as “public” and “internal” are not allowed for interface members. That's because the access modifier for the interface itself determines the access level for all members defined in the interface. Hence, adding an access modifier to an interface member would be redundant.
I think this is because when a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface.
So making something 'virtual' really does not make sense in this case, since virtual means that you intend to override it in an inherited class. Implementing an interface explicitly and making it virtual would be contradictory. Which also may be why the compiler disallows this.
To work around it I think csharptest.net's or Philip's answer sounds like it would do the trick
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