views:

30

answers:

2

So, I create an array:

TorrentItem[] torrents = new TorrentItem[10];

The TorrentItem control has a method called SetTorrentName(string name):

private void SetTorrentName(string Name)
{
    label1.Text = Name;
}

I'm using a for loop to populate 10 TorrentItems like so:

private TorrentItem[] GetTorrents()
{
    TorrentItem[] torrents = new TorrentItem[10];
    string test = "";

    for (int i = 0; i < 10; i++)
    {
          test = i.ToString();
          TorrentItem[i].SetTorrentName(test); //I get a null reference error here. 
          //What am I doing wrong?
    }
+6  A: 

You create an array of references to 10 objects, but you do not create the 10 objects in the array. All array elements are null until initialized otherwise.

for( int i = 0; i < 10; ++i )
{
    torrents[i] = new TorrentItem();
    /* do something with torrents[i] */
}

However, the name initialization could probably be put into the constructor.

Timbo
+1  A: 

You need to initialize each individual TorrentItem:

for (int i = 0; i < 10; i++)
{
      TorrentItem[i] = new TorrentItem(); //Initialize each element of the array
      test = i.ToString();
      TorrentItem[i].SetTorrentName(test); //I get a null reference error here. 
      //What am I doing wrong?
}
msergeant