0

Theese are my classes:

class Reply {
}

class VotableReply : Reply {
}

class Question : VotableReply {
}

class Answer : VotableReply {
}

class Comment : Reply {
}

Now, I want to add new class which will be common to Comment and Answer. But I cant really do that, because Answer and Question has common ancesor.

I think graph is easier to visualize problem

So, is there any way to add new class without using interfaces?

  • [Multiple inheritance](https://stackoverflow.com/questions/178333/multiple-inheritance-in-c-sharp) isn't supported by .NET, so an interface is _probably_ your best bet. – ProgrammingLlama May 11 '18 at 02:13

1 Answers1

2

Sometimes, inheritance is not the best choice. Maybe, it's better to use composition here:

class NewClass : Reply {
    private Comment comment;
    private Answer answer;

    NewClass() {
        comment = new Comment();
        answer = new Answer();
    }

    void CommentMethod() {
        comment.CommentMethod();
    }

    void AnswerMethod() {
        answer.AnswerMethod();
    }
}

So, now NewClass has functionality of Comment and Answer. Also, you can replace Reply with an interface, or add a new interface.

Backs
  • 24,430
  • 5
  • 58
  • 85