Search code examples
for-loopnullreferenceexceptionlistviewitem

Null Reference Exception with ListViewItem


I have the following code:

class Album
{
    private string name;

    private Music[] musics;
    private const int MAX_MUSICS = 100;
    private ListViewItem[] back;

    public ListViewItem[] GetTitles()
    {
        for (int i = 0; i < MAX_MUSICS; i++)
            if (musics[i].Title != null)
                back[i] = new ListViewItem(musics[i].Title);

        return back;
    }
}

At the line back[i] = new ListViewItem(musics[i].Title), I get a NullReferenceException. I dont know why because in the debuger musics[i].Title has a value and its even checked.


Solution

  • You need to tell how many elements 'back' array will have before you enter elements to it e.g.

        public ListViewItem[] GetTitles()
        {
            back = new ListViewItem[MAX_MUSICS]; // initialize array
    
            for (int i = 0; i < MAX_MUSICS; i++)
                if (musics[i].Title != null)
                    back[i] = new ListViewItem(musics[i].Title);
    
            return back;
        }
    

    Also make sure that your MAX_MUSICS is not bigger than size of musics array, otherwise you will hit into another exception