5

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?

2
  • 1
    You can implement the interface members/methods as abstract in MyBase class. Commented Jun 23, 2017 at 12:29
  • @Roman your right i wasn't thinking... Commented Jun 23, 2017 at 13:55

1 Answer 1

11

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

Sign up to request clarification or add additional context in comments.

1 Comment

Marked as the answer even tho i figured out this way on my own.. wasn't thinking, but thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.