5

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.

Jayakumar Thangavel
  • 1,884
  • 1
  • 22
  • 29

5 Answers5

7

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();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Tim Rutter
  • 4,549
  • 3
  • 23
  • 47
1

You have to add a Highscore to the array first, for example:

highscoresArray[0] = new Highscore();
Marce
  • 467
  • 1
  • 6
  • 10
1

That's because you've created an array, set its length, but never actually instantiated any of its elements. One way to do so would be:

Highscore[] highscoresArray = new Highscore[10];
highscoresArray[0] = new Highscore();
Aly Elhaddad
  • 1,913
  • 1
  • 15
  • 31
0

Maybe you need to initialize every item of the array:

 for (int i = 0; i < highscoresArray.length; i++)
 {
      highscoresArray[i] = new Highscore();
 }
CR0N0S.LXIII
  • 349
  • 2
  • 11
0

.. Or use a Struct

struct Highscore
{
    public int score;
}
Dmitriy Gavrilenko
  • 300
  • 1
  • 3
  • 18