[Solved] C#: Why does an intermediate array need to be used for defining a jagged array?


The reason is that a jagged array is actually an array of arrays of values.

Since arrays are objects, reference types, it means that if you construct a jagged array with room for 10 arrays, all those array references are initialized to null.

In other words:

int[][] a = new int[10][];
a[0][0] = 10;

throws NullReferenceException.

The code can be thought of like this:

int[][] a = new int[10][];

int[] temp = a[0]; // this works, but temp is now null
temp[0] = 10;      // throws NullReferenceException

Either you assign a fully populated array into the first slot, or you assign an initialized array without the values, like this:

for (int i = 0; i < 10; i++)
{
    serialisableHighScores.scores[i] = new int[3];
    serialisableHighScores.scores[i][0] = _highScores[i].date;
    serialisableHighScores.scores[i][1] = _highScores[i].score;
    serialisableHighScores.scores[i][2] = _highScores[i].questionsAsked;
}

Now, that’s just the explanation of why it crashes on your end. The best option you have available is not to use arrays like this, that is, don’t use 2-dimensional arrays to keep one list of related values, instead use objects:

public class Score
{
    public Score(DateTime date, int score, int questionsAsked)
    {
        Date = date;
        Score = score;
        QuestionsAsked = questionsAsked;
    }

    public DateTime Date { get; }
    public int Score { get; }
    public int QuestionsAsked { get; }
}

Additionally, arrays are good for fixed size things but in general it’s usually better to use lists:

var serializableHighScores = new List<Score>();
for (int i = 0; i < 10; i++)
{
    serializableHighScores.Add(new Score(_highScores[i].date, _highScores[i].score, _highScores[i].questionsAsked));
}

Though given the name of your variable, if you need to adhere to some badly designed (my opinion) serializing format with arrays of arrays it’s probably better to just stick with your code.

1

solved C#: Why does an intermediate array need to be used for defining a jagged array?