3

I am using a multidimensional array to keep track of answers:

public string[,] answersArray = new string[50, 10];

The first dimension of the array keeps track of questions (max. 50 questions), whereas the second dimension keeps track of each question's answers (max. 10). The amount of answers for each question is variable. Upon loading a question, I want to determine the amount of answers for that particular question. Then I can use that amount in a for loop to load and show these answers. Is there an easy way to obtain this, or would I have to write something myself? I know I could just declare another array to keep track of the amount of answers for each question, and just use that to get it done, but I was just wondering if there was an easier solution.

2 Answers 2

8

It sounds like you don't want a rectangular array as you've currently got, but instead an array of arrays, e.g.

string[][] answers = new string[50][];

Then you can populate each array with an array of the right size.

However, another alternative would be to avoid using arrays entirely - use List<T> which will grow as you need it to. In particular, you might want to have a List<Question> where a Question contains the question text itself and a List<Answer> (or possibly just a List<string>) for the answers.

The fact that arrays need to be sized up-front is one reason they should be considered "somewhat harmful".

If you really want to stick with your original approach, then obviously you know you've got 10 elements in each "row" of the array - you'd have to loop to find the first null value (if any) to indicate how many answers have actually been populated.

Sign up to request clarification or add additional context in comments.

1 Comment

In retrospect using Lists would've been better indeed. It's been a while since I last coded in C#, and since the application I'm writing is very small, I started out working with arrays. Thanks for the insight, this is very helpful!
3
var dim1 = answersArray.GetLength(0); // 50
var dim2 = answersArray.GetLength(1); // 10

2 Comments

I found this answer somewhere else as well, but as I said, the amount of answers in the second dimension of the array is variable. Question 1 could have 4 answers, whereas question 2 could have 6 answers, and 3 could have 10.
Referring to John skeets answer then :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.