Seabizkit
Seabizkit

Reputation: 2415

c# interface, abstract class, force inherited class not abstract class

Is there away to for member which inherit a base class which has an interface to implement that interface.

Some interface

public interface ICanWork
{
     void DoSomething();
}

some abstract class

public abstract Class MyBase : ICanWork
{
     // I do not want to implement the ICanWork but instead want the derived class which inherit it
}

class which i inherit the base class

public class House : MyBase
{
     // i want the compiler to know that it needs to implement ICanWork 
}

This didn't work as i would expect.

Is the only way to achieve this by putting the Interface on the Class inherit the base class?

e.g.

public class House : MyBase, ICanWork
{
    
}

Any useful suggestions?

Upvotes: 5

Views: 2542

Answers (1)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37113

You have to implement the interface within that class that implements your interface, even if your class is abstract. However you can make your implementation of that method also abstract which forces all deriving classes to implement it:

public abstract Class MyBase : ICanWork
{
     public abstract void DoSomething();
}

When you now define a class deriving your asbtract base-class you also have to implement that method:

public class House : MyBase
{
    public override void DoSomething() { ... }
}

From MSDN:

Like a non-abstract class, an abstract class must provide implementations of all members of the interfaces that are listed in the base class list of the class. However, an abstract class is permitted to map interface methods onto abstract methods

Upvotes: 11

Related Questions