r/csharp•
esssential

Is there a preferred way of doing this? (Generic class inheriting from non-generic class)

Is something like this the best way of inheriting from non-generic classes?

public abstract class Answer
{
    private readonly Question _question;
    public Question Question => _question;

    protected Answer(Question question)
        => _question = question;
}

public abstract class Answer<TQuestion> : Answer
    where TQuestion : Question
{
    private readonly TQuestion _question;
    public new TQuestion Question => _question;

    protected Answer(TQuestion question) : base(question)
        => _question = question;
}

public class SingleAnswer : Answer<SingleOptionQuestion>
{
    private readonly Choice _choice;
    public Choice Choice => _choice;

    public SingleAnswer(SingleOptionQuestion question, Choice choice) : base(question)
        => _choice = choice;
}

public class MultiAnswer : Answer<MultiAnswerQuestion>
{
    private readonly IEnumerable<Choice> _choices;
    public IEnumerable<Choice> Choices => _choices;

    public MultiAnswer(MultiAnswerQuestion question, params Choice[] choices) : base(question)
        => _choices = choices;
}

public class OpenAnswer : Answer<OpenQuestion>
{
    private readonly OpenChoice _choice;
    public OpenChoice Choice => _choice;

    public OpenAnswer(OpenQuestion question, OpenChoice choice) : base(question)
        => _choice = choice;
}

Posted Mar 28, 2018, 8:47 PM UTC

810
Loading comments…