Reputation: 45
Is it possible to store a Class that contains a List inside an array?
I am having some trouble with this concept.
Here's my code:
My Class Called "arrayItems":
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EngineTest
{
[Serializable] //List olarak save etmemiz için bu gerekli.
public class arrayItems
{
public List<items> items = new List<items>();
}
}
Here's the definition of my Array called "tileItems":
public static arrayItems[, ,] tileItems;
Here's how I create my Array:
Program.tileItems = new arrayItems[Program.newMapWidth, Program.newMapHeight, Program.newMapLayers];
The problem I am facing is that the content of my Array is null. And I am getting this error:
Object reference not set to an instance of an object.
When I try to populate the List inside the array by Add() command I get the same error.
Can you direct me to the right direction please? Thanks in advance.
Upvotes: 0
Views: 2164
Reputation: 2812
You are creating and array of arrayItems
, which is a reference type, because you defined it as a class. So when you initialize your array, all elements will be assigned null
by default. That's why you get the error. You have to initialize each element of your array.
Upvotes: 2
Reputation: 2463
Since you are already initializing the list within the class definition you do not need to re-initialize the list property of arrayItems
within the loop.
You have an array that has a bunch of pointers that point to nothing. So you actually need to instiante a new arrayItems
in each array element first.
for (int i = 0; i < newMapWidth; i++)
{
for (int j = 0; j < newMapHeight; j++)
{
for (int k = 0; k < newMapLayers; k++)
{
arrayItems[i,j,k]= new arrayitem();
}
}
}
Upvotes: 2
Reputation: 14640
You need to initialise each list within the array:
for (int i = 0; i < newMapWidth; i++)
{
for (int j = 0; j < newMapHeight; j++)
{
for (int k = 0; k < newMapLayers; k++)
{
arrayItems[i,j,k] = new arrayItems();
}
}
}
first.
Upvotes: 6