Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create array of 100 new objects?

Tags:

arrays

c#

I'm trying something like that:

class point
{
public int x;
public int y;
}

point[] array = new point[100];
array[0].x = 5;

and here's the error: Object reference not set to an instance of an object. (@ the last line)

whats wrong? :P

like image 260
Patryk Avatar asked Nov 28 '22 17:11

Patryk


1 Answers

It only creates the array, but all elements are initialized with null.
You need a loop or something similar to create instances of your class. (foreach loops dont work in this case) Example:

point[] array = new point[100];
for(int i = 0; i < 100; ++i)
{
    array[i] = new point();
}

array[0].x = 5;
like image 179
Skalli Avatar answered Dec 19 '22 00:12

Skalli