Question Trying to create an array of class instances (System.NullReferenceException)

Merv

New member
Joined
Oct 26, 2022
Messages
3
Programming Experience
Beginner
Hello everyone,
I'm new on the forum and recently started learning C#, I'm still a beginner when it comes to programming.

I'm trying to make multiple instances of a class in the same way i would make an array but i get the following error:

System.NullReferenceException: 'Object reference not set to an instance of an object.'
Pawn[] was null.

Example:
Pawn[] Pawn = new Pawn[5];      

public void ReachPawn()
{
    Pawn[1].x = 5;
}

Can anyone tell me how to do this properly?
 
You need to allocate a Pawn object for each of the other array elements.
 
I figured it out, thanks!

Victory!:
Pawn[] pawn = new Pawn[5];

public void ReachPawn()
{
    for (int i = 0; i < 5; i++)
    {
        pawn[i] = new Pawn();
    }
    pawn[0].x = 4;
    Console.Write(pawn[0].x + " " + pawn[1].x);
    Console.ReadKey();
}
 
Last edited:
The best way to create and populate an array depends on the specific situation but you could populate that array where you're creating it:
C#:
Pawn[] pawn = new[]
              {
                  new Pawn { x = 4 },
                  new Pawn { x = 4 },
                  new Pawn { x = 4 },
                  new Pawn { x = 4 },
                  new Pawn { x = 4 }
              };
I would say that explicitly initialising an array that way is preferable, unless there's a specific reason to do otherwise.
 
The best way to create and populate an array depends on the specific situation but you could populate that array where you're creating it:
C#:
Pawn[] pawn = new[]
              {
                  new Pawn { x = 4 },
                  new Pawn { x = 4 },
                  new Pawn { x = 4 },
                  new Pawn { x = 4 },
                  new Pawn { x = 4 }
              };
I would say that explicitly initialising an array that way is preferable, unless there's a specific reason to do otherwise.
What i wrote here was just a simplified example, i actually need to initialize each pawn with unique values dynamically through the game. so yea i just use an array to make them exist and do the rest later depending on user input.
Also using the array makes it easy to give each pawn instance their own 'id' by using the for loop integer as an index in the class array.
 
In true object oriented programming, the reference to the object is the object's "ID". There is no need to associate another ID with it. It's people who are accustomed to procedural programming, or people who have to serialize/deserialize to a relational database who are typically concerned about object IDs.
 
Back
Top Bottom