Why Use Array Instantiation for Questions in C#?

0
1
Asked By CuriousCoder87 On

Hey everyone! I'm currently diving into C# through a course where we're building a quiz app. I noticed that one of our constructors has several parameters, and instead of providing each one directly, my instructor is using an array of the Question class to keep things cleaner. I'm just trying to understand the reasoning behind this approach.

Here's the constructor I'm talking about:

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 we instantiate it using an array:

Questions[] questions = new Questions[]
{
new Questions("What is the capital of Germany?",
new string[] {"Paris", "Berlin", "London", "Madrid"}, 1)
};

I also have an example of the usual (or "regular") way to instantiate it:

Questions questions = new("What is the capital of Germany?", new string[] { "Paris", "Berlin", "London", "Madrid" }, 1);

What's the advantage of using the array instantiation in this case?

1 Answer

Answered By CodingEnthusiast22 On

Using the array instantiation is a great way to manage multiple questions at once! It keeps your code neat, especially if you want to add more questions later without cluttering your main code. It’s definitely about improving readability and organization.

CuriousCoder87 -

Wow, that makes total sense! I didn't think about how messy it could get with multiple questions. Thanks for the clarity!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.