- Home /
Passing unknown parameter type and class inheritance (C#)?
Hey folks,
I'm still fairly new to OOP and I'm having trouble figuring out using baseclass and subclass object types.
In making a quiz, I've got an abstract Question class which has a number of subclasses for each category of question, i.e. Chemistry, Biology, Maths etc.
public class Question
{
public int questionID;
public string stem;
public string answer;
public string[,] distractors;
public string GetStem()
{
return stem;
}
public string GetAnswer()
{
return answer;
}
etc...
}
and the subclasses where an additional variable referencing an image or video:
[System.Serializable]
public class ChemistryQuestion : Question
{
public string chemistryRef;
}
[System.Serializable]
public class BiologyQuestion : Question
{
public string biologyRef;
}
[System.Serializable]
public class MathQuestion : Question
{
public string mathRef;
}
To store all the questions in a bank i used this class with methods to get, set and I/O to XML:
public class QuestionDatabase
{
public List<BiologyQuestion> bioQuestionBank = new List<BiologyQuestion>();
public List<ChemistryQuestion> chemQuestionBank = new List<ChemistryQuestion>();
public List<MathQuestion> mathQuestionBank = new List<MathQuestion>();
}
The biggest problem I've had is trying to pass these lists to other methods in order to display the questions without having to write 3 different methods for the 3 different subclass types. For example:
public void QuestionInitialise(List<??> qList);
{
//...code to sort through list and pull out details
PopulateQuestion(question, answers);
}
I tried using the baseclass as a type, however I got a 'cannot convert' error. I just feel that although I could work around it by writing multiple methods for each type, there must be a way of accomplishing this at runtime.
Any advice will be gratefully received! :)
Answer by Sergio7888 · Oct 10, 2016 at 02:18 PM
You can use a List<Question>
to hold any question subclass you have, in the method you can use: public void QuestionInitialise<T>(List<T> qList) where T:Question {
}
Thank you, that was exactly what I was looking for. Is there a similar way to declare a list variable without a specific type? That way I can save the passed list
public List<T> currentList;
public void QuestionInitialise<T>(List<T> qList) where T:Question
{
currentList = qList;
}
What is this technique called, so I can go read some documentation on it? :)