0

I have a public class (simplified):

  public class opening
    {
        public face side;
        public int start;
        public int length;

        public opening(){}
    }

I want an array of opening in another class

opening[] openings = new opening[4];

but when I try to assign a value to it, for instance:

this.openings[2].side = side;

I get "Object reference not set to an instance of an object" I can work around it using:

this.openings[2] = new opening();
this.openings[2].side = side;

but calling new opening(); for each element of the array feels odd, isn't there an easy way to instantiate every element of the array when creating it?

herisson
  • 128
  • 6
  • _"Isn't there an easy way to instantiate every element of the array when creating it?"_ -> A loop? – ProgrammingLlama May 15 '20 at 16:28
  • 3
    `opening[] openings = Enumerable.Range(0, 4).Select(_ => new opening()).ToArray();` –  May 15 '20 at 16:28
  • You may be better off using a `List` and adding values to that rather than a data structure (array) that implies there are existing elements already there. – Ian Mercer May 15 '20 at 16:30
  • Already answered here: https://stackoverflow.com/questions/9333232/instantiate-an-array-of-objects-in-simpliest-way – kvp2982 May 15 '20 at 16:32
  • @kvp2982, thanks this is it exactly i somehow didn't manage to find it, sorry for the duplicate. @IanMercer thanks, I'm not used to `List` and therefore didn't consider using it in the first place but it seems better and i will use it! – herisson May 15 '20 at 16:45

0 Answers0