Hey everyone! I'm currently learning C# and working on a quiz app in my course. In one part, we have a constructor for a 'Question' class that takes multiple parameters. My instructor is using an array of 'Question' objects to instantiate them instead of entering each parameter separately, and I'm trying to understand the reasoning behind this.
Here's a quick look at the constructor:
public string QuestionText { get; set; }
public string[] Answers { get; set; }
public int CorrectAnswerIndex { get; set; }
public Questions(string question, string[] answers, int answerIndex)
{
QuestionText = question;
Answers = answers;
CorrectAnswerIndex = answerIndex;
}
And here's how they're instantiated using an array:
Questions[] questions = new Questions[]
{
new Questions("What is the capital of Germany?",
new string[] {"Paris", "Berlin", "London", "Madrid"}, 1)
};
Versus a more traditional instantiation like this:
Questions questions = new("What is the capital of Germany?", new string[] {"Paris", "Berlin", "London", "Madrid"}, 1);
Could someone explain why we might prefer the array instantiation in this situation?
Thanks! If you need more details, let me know!
2 Answers
Using an array to instantiate questions is super handy if you plan on adding multiple questions later without cluttering your code. This way, you keep everything organized and readable, plus you can easily expand the array when needed!
The array method allows for multiple instantiations in one go, which can be easier to manage, especially if you're working on a quiz with a lot of questions. The readability factor is key here! But yeah, some might say it's not the best practice depending on the situation. Also, just a small note: your class name should ideally be 'Question' instead of 'Questions'.
Got it! That makes sense! I prefer 'Questions' because it sounds more intuitive, but I'll stick with 'Question' since that's what the instructor used.
Haha, I totally get you! It's a lot cleaner to just add more questions in the array rather than repeating the entire instantiation process for each one.