Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring an Array from a Class in C#

I want to create an Array of "Highscore" objects that I defined with a class.
I'm always getting a NullReferenceException when I try to set or read the Value of a specific Array content.

It does work when I use a single Highscore object instead of an Array.

It also does work when I use an integer array instead of an Highscore Array.

Code

class Highscore
{
    public int score;
}
class Program
{
    static void Main()
    {
        Highscore[] highscoresArray = new Highscore[10];
        highscoresArray[0].score = 12;
        Console.WriteLine(highscoresArray[0].score);
        Console.ReadLine();
    }
}

System.NullReferenceException:

highscoresArray[] was null.

like image 711
SpacersChoice Avatar asked Jan 01 '23 12:01

SpacersChoice


1 Answers

in this code:

Highscore[] highscoresArray = new Highscore[10];

you instantiate an array of Highscore objects but you do not instantiate each object in the array.

you need to then do

for(int i = 0; i < highscoresArray.Length; i++)
    highscoresArray[i]  = new Highscore();
like image 165
Tim Rutter Avatar answered Jan 08 '23 07:01

Tim Rutter