Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly implementing an interface with an abstract method

Here is my interface:

public interface MyInterface {
    bool Foo();
}

Here is my abstract class:

public abstract class MyAbstractClass : MyInterface {
    abstract bool MyInterface.Foo();
}

This is the compiler error: "The modifier 'abstract' is not valid for this item.

How should I go on about explicitly implementing an abstract with an abstract method?

like image 783
acermate433s Avatar asked Oct 28 '10 16:10

acermate433s


People also ask

Can an abstract method implement an interface?

Java Abstract class can implement interfaces without even providing the implementation of interface methods. Java Abstract class is used to provide common method implementation to all the subclasses or to provide default implementation.

What happens when an abstract class implements an interface?

Other hand, abstract class is a class that can have implementation of some method along with some method with just declaration, no implementation. When we implement an interface to an abstract class, its means that the abstract class inherited all the methods of the interface.

Does abstract class have to implement all interface methods?

Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class.

Can we use abstract method in interface in C#?

You can't, basically. Not directly, anyway. You can't override a method which is explicitly implementing an interface, and you have to override an abstract method.


2 Answers

You can't, basically. Not directly, anyway. You can't override a method which is explicitly implementing an interface, and you have to override an abstract method. The closest you could come would be:

bool MyInterface.Foo() {
    return FooImpl();
}

protected abstract bool FooImpl();

That still implements the interface explicitly and forces derived classes to actually provide the implementation. Are those the aspects you're trying to achieve?

like image 97
Jon Skeet Avatar answered Nov 15 '22 20:11

Jon Skeet


You have to use an implicit implementation of the interface member instead of an explicit implementation:

public abstract class MyAbstractClass : MyInterface
{
    public abstract bool Foo();
}
like image 24
Mike Dour Avatar answered Nov 15 '22 20:11

Mike Dour