balexandre
balexandre

Reputation: 75093

How to have n variables in C#

imagine this code

for (int iDay = 1; iDay <= total_days; iDay++)
{

    question = CheckString(s.challenge_1_q);
    answer = CheckStringA(s.challenge_1_a);

    // more here
}

but what I really have is from challenge_1_q to challenge_24_q and challenge_1_a to challenge_24_a

what is my best option to have dynamic variables as today it's 24, "tomorrow" could be only 18.

is the use of dynamic the proper way? or I really need to have a switch and forget about dynamism ?

Upvotes: 0

Views: 120

Answers (2)

Javed Akram
Javed Akram

Reputation: 15344

You can also create Structure

struct QuestionBank
{
   public string Question;
   public string Answer;            
}

And use Something like this

 QuestionBank []Quiz = new QuestionBank[n]; //n is number of question and answers
 Quiz[0].Question = "SomeQuestion";
 Quiz[0].Answer = "SomeAnswer";

 Quiz[1].Question = "SomeAnotherQuestion";
 Quiz[1].Answer = "AnswerAsWell";

 .....

 Quiz[n].Question = "nth Question";
 Quiz[n].Answer = "nth AnswerAsWell";

Upvotes: 0

Greg Sansom
Greg Sansom

Reputation: 20840

Create a class called QuestionAnswer, then store a List on s. The accessing code will look like this:

question = CheckString(s.QuestionAnswers[i].Question);
answer = CheckStringA(s.QuestionAnswers[i].Answer);

The QuestionAnswer class:

public class QuestionAnswer
{
  public string Question{get; set;}
  public string Answer{get; set;}
}

And the definition on your existing class:

public List<QuestionAnswer> QuestionAnswers = new List<QuestionAnswer>();

Instead of having dozens of variables, you add dozens of items to the list:

QuestionAnswer qa = new QuestionAnswer();
qa.Question = "What letter comes after A?";
qa.Answer = "B";
QuestionAnswers.Add(qa);
//repeat for all your questions.

Upvotes: 3

Related Questions