How to creating an a array of class objects

  • Thread starter Thread starter Clinton Daniel
  • Start date Start date
C

Clinton Daniel

I have an array like this:

MyClass[] myArray;

In a method I allocate it depending on how many rows in the DataTable:

myArray = new MyClass[myDataTable.Rows.Count

However, when I try to access them in a foreach loop, they aren't instantiated.

foreach(MyClass tmpClass in myArray)
{
tmpClass.myField = 1; // set to 1 as a test
}

WTF is going wrong?
 
You aren't populating the array with new instances this way. What happens is
that the myArray gets initialized with a specific amount of slots; all of
them equals null.

You need to run a loop equal to the length of the array, instantiating your
MyClass and assigning it to the right index of the myArray.
 
You need to do this before using the foreach statement.

for(int i=0; i<myArray.Count; i++)
{
myArray = new MyClass();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top