2
  • I have an interface (Ae) that has a list of objects (List) from another interface (Ba).
  • I have a class that implements interface Ae.
  • I have several classes that implement the Ba interface.

Is there any way to make each class that implements interface Ae has a List of one of the concrete classes that implement Ba as property?

public interface IQuestion
{
    IAnswerOption[] Answers { get; set; }
}

public interface IAnswerOption
{
    int Id { get; }
    bool IsCorrect { get; set; }
}

public class AnswerOptionText : IAnswerOption
{
    public int Id { get; }
    public bool isCorrect;
    public string ansText;
}

public class AnswerOptionImage : IAnswerOption
{
    public int Id { get; }
    public bool isCorrect;
    public string imgSlug;
}

public class AudioQuestion : IQuestion
{
    public AnswerOptionImage[] Answers;
    public string audioName;
}

public class TextQuestion : IQuestion
{
    public AnswerOptionText[] Answers { get; set; }
    public string questionText { get; set; }
}

When I try it, AudioQuestion and TextQuestion doesn't allow me to use AnswerOptionImage[] and AnswerOptionText[] respectively.

Visual Studio says that I need to implement interface member IQuestion.Answers, but this is not what I intend.

If someone can help me I would be very grateful. Thanks.

1 Answers1

4

It seems that using generics for your IQuestion interface will be a good fit:

public interface IQuestion<T> where T: IAnswerOption
{
    T[] Answers { get; set; }
}

public class AudioQuestion : IQuestion<AnswerOptionImage>
{
    public AnswerOptionImage[] Answers{ get; set; }
    public string audioName;
}

public class TextQuestion : IQuestion<AnswerOptionText>
{
    public AnswerOptionText[] Answers { get; set; }
    public string questionText { get; set; }
}
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • Thanks. Imagine that in the future I want that class TextQuestion receives both AnswerOptionText[] and AnswerOptionImage[]. What would be the best approach to do this? What do you suggest? – Diogo Ferreira Aug 12 '20 at 22:55
  • @DiogoFerreira since there is no build in discriminated unions in C# ATM you can try implement some kind of `OneOf` type (multiple of them with different number of parameters) or use your current one allowing any answer type. – Guru Stron Aug 12 '20 at 23:08
  • I didn't understand what do you mean by OneOf (where can I see more about it?). How can I use my current one allowing any answer type? This is enough public class TextQuestion : IQuestion? Sorry for the questions but I am a beginner and it is all so confusing for me. – Diogo Ferreira Aug 12 '20 at 23:21