When creating an array of a reference type (MyArrObj
in your case), it is required that you allocate memory for each array element (using new
operator) in addition to allocating memory for the array itself.
Array of Reference types
For example, if you create an MyArrObj array,
MyArrObj[] objectArray = new MyArrObj[3];
Then the array elements objectArray[0]
to objectArray[2]
would still be null
. A separate initialization is required.
objectArray[0] = new MyArrObj();
Only when the above step is done can you access the members of the array element.
objectArray[0].SomeMethod();
SomePropertyType readProperty = objectArray[0].SomeProperty;
If you skip the array element initialization then trying to access a member of the array element would give a System.NullReferenceException
objectArray[0].SomeMethod(); // throws NullReferenceException
because
objectArray[0];
is null
.
You can check this using
if(objectArray[0] == null)
{
Console.WriteLine("objectArray[0] is null");
}
Array of Value types
If you know the array before hand, then you can use the initialization pointed out by @clonked.
For value types like built in types(like int, float
, structs, etc. you need not initialize each array element.
For example, if you create an int array,
int[] intArray = new int[3];
Then the array elements intArray[0]
to intArray[2]
have the memoery allocated and values can be assigned to them.
intArray [0] = 1;
Check your GetData()
So your GetData()
method should include code like this,
private MyArrObj[] GetData()
{
int numberOfObjects = GetNumberOfObjects(); // Get the number of objects at runtime
MyArrObj[] objectArray = new MyArrObj[numberOfObjects];
for (int i = 0; i < numberOfObjects; i++)
{
objectArray[i] = new MyArrObj();
}
return objectArray;
}
More information