0

I receive a null reference exception at Shapes[0].DamageofShape[0] = 7;. Do I need to do another initialization somewhere?

   public struct TestArrayStruct
    {
        public int[] DamageofShape;
    }

class Program
    {

        static void Main(string[] args)
        {
            TestArrayStruct[] Shapes = new TestArrayStruct[5];

            Shapes[0].DamageofShape[0] = 7;
        }
     }

1 Answers1

4

You need to initialize Shapes[0].DamageofShape1, whose value is null by default:

Shapes[0].DamageofShape = new int[4];

You could do this in the constructor as well:

public struct TestArrayStruct
{
    public int[] DamageofShape;

    public TestArrayStruct(int size)
    {
        this.DamageofShape = new int[size];
    }
}

However, then you would have to instantiate your struct with the constructor to take advantage of it:

Shapes[0] = new TestArrayStruct(4);
Shapes[0].DamageofShape[0] = 7;


1a previous version if this answer said you had to instantiate Shapes[0], which was incorrect
Andrew Whitaker
  • 119,029
  • 30
  • 276
  • 297