0

I am trying to create a 2-D array of integer triplets R, G and B using the following code:

 BitmapColours [,] PrevImage = new BitmapColours [1, 1];

    public class BitmapColours
    {
        public  int R { get; set; }
        public  int B { get; set; }
        public  int G { get; set; }

    }

but when I try to set a triplet value using

PrevImage[0,0].R = -1;

I get the error "Object Reference not set to an instance of the Object"

Jay Li
  • 31
  • 3

1 Answers1

3

The error you are getting happens because you're trying to access a field R using a null reference. (See What is a NullReferenceException, and how do I fix it? for the C# error, and https://en.wikipedia.org/wiki/Null_pointer for information about null in general).

According to the official Microsoft C# guide (https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/), the following occurs when an array is first created:

The default values of numeric array elements are set to zero, and reference elements are set to null

Your type BitmapColours is defined as a class, which is a reference type (see https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/classes), so every entry in your array is initialized to null. You need to first create an instance of your class for that index, and then your code will work. It should look something like this:

BitmapColours [,] PrevImage = new BitmapColours [1, 1];
PrevImage[0,0] = new BitmapColors();
PrevImage[0,0].R = -1;
Dory L.
  • 133
  • 8