Patryk
Patryk

Reputation: 3152

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

Upvotes: 4

Views: 44018

Answers (6)

Palec
Palec

Reputation: 13581

Sometimes LINQ comes in handy. It may provide some extra readability and reduce boilerplate and repetition. The downside is that extra allocations are required: enumerators are created and ToArray does not know the array size beforehand, so it might need to reallocate the internal buffer several times. Use only in code whose maintainability is much more critical than its performance.

using System.Linq;

const int pointsCount = 100;
point[] array = Enumerable.Range(0, pointsCount)
    .Select(_ => new point())
    .ToArray()

Upvotes: 0

Skalli
Skalli

Reputation: 2817

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;

Upvotes: 12

Charp
Charp

Reputation: 198

int[] asd = new int[99];
for (int i = 0; i < 100; i++)
    asd[i] = i;

Something like that?

Upvotes: 1

Ohad Schneider
Ohad Schneider

Reputation: 38142

As the other answers explain, you need to initialize the objects at each array location. You can use a method such as the following to create pre-initialized arrays

T[] CreateInitializedArray<T>(int size) where T : new()
{
    var arr = new T[size];
    for (int i = 0; i < size; i++)
        arr[i] = new T();
    return arr;
}

If your class doesn't have a parameterless constructor you could use something like:

T[] CreateInitializedArray<T>(int size, Func<T> factory)
{
    var arr = new T[size];
    for (int i = 0; i < size; i++)
        arr[i] = factory();
    return arr;
}

LINQ versions for both methods are trivial, but slightly less efficient I believe

Upvotes: 1

THX-1138
THX-1138

Reputation: 21750

You can change class point to struct point in that case new point[500] will create an array of points initialized to 0,0 (rather than array of null's).

Upvotes: 6

Paolo Tedesco
Paolo Tedesco

Reputation: 57222

When you do

point[] array = new point[100];

you create an array, not 100 objects. Elements of the array are null. At that point you have to create each element:

array[0] = new point();
array[0].x = 5;

Upvotes: 7

Related Questions