Cannot initialize an array, IndexOutOfRangeException

Hello,

I assume I am making a syntactical mistake, but as I don’t really now what this called and even searching for the error messages, I need your help.

I have a custom class with variables and also arrays in it. I try to initialize it and then adding manually values to the array.

public CustomClass[] myClass;

myClass= new CustomClass[8];

        myClass[0].value = 100;
        myClass[0].list[0] = 4;
        myClass[0].list[1] = 120;
        myClass[1].value = 100;
        myClass[1].list[0] = 4;
        myClass[1].list[1] = 120;
        //etc...

I get NullReferenceException: Object reference not set to an instance of an object on line myClass[0].value = 100;

I also tried :

    public CustomClass[] myClass;
    
    myClass[8]= new CustomClass();

I get IndexOutOfRangeException: Index was outside the bounds of the array

Any help is appreciated :slight_smile:

You need to assign a new CustomClass to myClass[0];

 myClass[0] = new CustomClass();

Add that line before assigning the variables

myClass[0] = new CustomClass();
myClass[0].value = 100;
myClass[0].list[0] = 4;
myClass[0].list[1] = 120;

It also looks like you have another array inside your customclass make sure you define the array size for that also

It worked,

thank you :slight_smile: