Other than the typo in the question:
obj.m = new test();
obj.z = new test();
The test array in
Testdata.z
must be initialized to a correctly sized array before you can put any content in the array.
public class Testdata {
public string x;
public string y;
public test[] z = new test[named constant for correct size of the array];
}
So the next question is: At the point where you create the
Testdata
instance, do you know how many entries the
Testdata.z
array must contain or is its size dynamic?
It seems most likely that the size is not pre-determined, so changing the declaration of z from an array of test to a List<test> would be a good solution:
public class Testdata {
public string x;
public string y;
public List<test> z = new List<test>();
}
Then the test instances can be added to the z collection with:
test theTest = new test();
obj.z.Add(new theTest);
See
List< T > class[
^] for more information about using that collection type.
Edit - Matt T Heffron: followup from comments.
1. initialize the z array with the appropriate size when Testdata is created, from outside of the Testdata class right after it is created with new Testdata()
Testdata obj = new Testdata();
obj.z = new test[named constant for correct size of the array];
2. initialize the array as in #1 to an empty array and then manage the size of the array manually whenever you add items to the array (probably using System.Array.Resize() )
Testdata obj = new Testdata();
obj.z = new test[0];
Then everywhere you need to add a new element to the array:
Array.Resize(ref obj.z, obj.z.Length+1);
obj.z[obj.z.Length-1] = new test();
This is very inefficient, so don't do this unless you have no other choice!
3. If you can, create and collect all of the instances of the test class for a given Testdata in a List and when they are all there, then set the Testdata.z to the collection converted to an array. E.g., using Linq this would be obj.z = testsList.ToArray();
Testdata obj = new Testdata();
List<test> testsList = new List<test>();
test nt = new test();
testsList.Add(nt);
obj.z = testsList.ToArray();