Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement an interface explicitly with a virtual method?

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?

like image 228
Jader Dias Avatar asked Jul 26 '10 16:07

Jader Dias


People also ask

Can we use virtual method in interface?

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.

Can we declare virtual method in interface C#?

C# methods in interfaces are declared without using the virtual keyword, and overridden in the derived class without using the override keyword.

Can a method derived from interface be marked as virtual?

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 .

CAN interface have internal methods?

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.


1 Answers

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

like image 189
7wp Avatar answered Oct 12 '22 07:10

7wp