Search code examples
c#loopsmenustrip

ForEach Loop exiting when handler is created - C#


In my program, I am listing every logical drive inside of a menustrip. To accomplish this, I use the following code

private ToolStripMenuItem[] getAllDrives()
    {
        //find the number of drives
        int arrayLength = DriveInfo.GetDrives().Count();

        //create array that can hold all drives
        ToolStripMenuItem[] drives = new ToolStripMenuItem[arrayLength];

        //populate array
        int currentSlot = 0;
        foreach (DriveInfo d in DriveInfo.GetDrives())
        {
            drives[currentSlot].Name = d.Name;
            drives[currentSlot].Tag = d.Name;
            drives[currentSlot].Text = d.Name + " " + d.VolumeLabel;
            drives[currentSlot].Click += new EventHandler((se,e1) => driveClick(d.Name));
            currentSlot++;
        }
        return drives;
    }

However, it appears that for whatever reason, the loop exits when the drives[currentSlot].Name is modified. Why is it doing this?


Solution

  • Because you forgot to initialize drives[currentSlot]. It is null and you get an exception (System.NullReferenceException)

     drives[currentSlot] = new ToolStripMenuItem();