cookies cookies - 3 days ago 5
C# Question

How to have a variable that could be a one of three predefined objects

My code lets a user create a question and answer pair. There are three types the answer can be: either a NumericalAnswer, RangedAnswer or a ShortAnswer (a string).

I have the base Question Class:

class QuestionClass
{
private string question;
private AnswerClass answer;

public string Question
{
get { return question; }
set { question = value; }
}

public AnswerClass Answer
{
get { return answer; }
set { answer = value; }
}

public QuestionClass(string question, AnswerClass answer)
{
this.question = question;
this.answer = answer;
}
}


All the answer types are inherited from an empty base class AnswerClass. The Answer classes are:

class NumericalAnswer : AnswerClass
{
private float answer;

public float Answer
{
get { return answer; }
set { answer = value; }
}
}

class RangedAnswer : AnswerClass
{
private float lowerBound;
private float upperBound;

public float LowerBound
{
get { return lowerBound; }
set { lowerBound = value; }
}

public float UpperBound
{
get { return upperBound; }
set { upperBound = value; }
}
}

class ShortAnswer : AnswerClass
{
private string[] answer;

public string[] Answer
{
get { return answer; }
set { answer = value; }
}
}


However, for example, if I create a question with a RangedAnswer and try to access the lowerBound variable I can't. If you know how I would be able to have multiple Answer classes.

Answer

You could use generics:

public class QuestionClass<T> where T : AnswerClass
{
    private string question;
    private T answer;

    public string Question
    {
        get { return question; }
        set { question = value; }
    }

    public T Answer
    {
        get { return answer; }
        set { answer = value; }
    }

    public QuestionClass(string question, T answer)
    {
        this.question = question;
        this.answer = answer;
    }
}

Sample Usage:

var ra = new RangedAnswer();
ra.LowerBound = 10;
ra.UpperBound = 20;
var q = new QuestionClass<RangedAnswer>("Test range?", ra);
q.Answer.LowerBound.Dump();
Comments