What i mean is i am trying to store 2 different types of custom objects in 1 array. I have tried and array of type Object but run into problems when i then try to access methods of the individual objects as there type is not know.
Why are you storing different types in an array? do they all do similar things? If this is the case then you will want to google interfaces in c#. This will let you work with an object regardless of its type, as long as it implements the interface.
If this isn't the case, then I suggest you re-think why you are storing 2 types in one array. I would instead create 2 separate arrays based on type.
If you absolutely must have both in one array, then check their type with the "is" keyword.
if (myarray[0] is MyObject)
{
//dosomething
}
The last method involves casting (internally) which tends to be slow. The interface method is probably the best.
I have 2 types of questions both have similar properties, and reach use an interface to define the methods which are common to both. My array needs to contain various question type 1 and type 2 which forms the quiz. The program moves through the array of questions displaying each one based on its type, it then stores the user’s responses. So I need everything in one array. How would this usually be achieved?
public class MultipleChoiceQuestion : IQuestion
{
private string answer = null;
private string question = null;
public MultipleChoiceQuestion()
{
}
public string Question
{
get
{
return question;
}
set
{
question = value;
}
}
public string Answer
{
set
{
answer = value;
}
}
public bool Evaluate(string response)
{
return (response.ToUpper().Equals(answer.ToUpper()));
}
}
create another class the same way - implementing the interface.
then you can use those classes like so:
ArrayList questions = new ArrayList();
public void DoQuiz()
{
MultipleChoiceQuestion q1 = new MultipleChoiceQuestion();
q1.Question = "Insert my question here with options";
q1.Answer = "C";
AskQuestions();
}
public void AskQuestions()
{
foreach (IQuestion q in questions)
{
Console.WriteLine(q.Question);
Console.Write("Answer: ");
string answer = Console.ReadLine();
Thanks, yea that’s what I’ve done except i was adding additional methods into each question which weren't part of the interface so they weren’t exposed when i added the questions to the list.
Thanks for the help learning slowly.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.