Patryk Patryk - 1 month ago 5
C# Question

How to create array of 100 new objects?

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

Answer

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;