-1

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?

w0f
  • 864
  • 6
  • 22
  • For future question please provide exception details in the pose - "loop exits" is very non-specific explanation of problem. As it stands now your question is already answered in "Array Elements" section of [What is NullReferenceException and how to fix it](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) question. – Alexei Levenkov Jul 05 '14 at 19:22
  • I will be more specific in future posts. The odd thing with this scenario is that no exception was being thrown, making it hard for me to pinpoint the exact cause of the error. – w0f Jul 05 '14 at 19:25
  • "no exception was being thrown" is very unlikely - you may be eating all exceptions in caller or above. Consider reading on good practice of exception handling i.e. starting http://stackoverflow.com/questions/204814/is-there-any-valid-reason-to-ever-ignore-a-caught-exception. – Alexei Levenkov Jul 05 '14 at 19:30
  • 1
    @AlexeiLevenkov possible if this code is called in a Form_Load event in a 64bit environment from the Visual Studio Debugging Session --- oh well --- http://stackoverflow.com/questions/4933958/vs2010-does-not-show-unhandled-exception-message-in-a-winforms-application-on-a – Steve Jul 05 '14 at 19:56

2 Answers2

2

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

 drives[currentSlot] = new ToolStripMenuItem();
Sergey Berezovskiy
  • 215,927
  • 33
  • 392
  • 421
EZI
  • 14,547
  • 2
  • 24
  • 31
0

You are not initializing the item at drives[currentSlot] before attempting to access its properties, as such you'll likely be getting a NullReferenceException thrown, terminating your loop. Try adding:

drives[currentSlot] = new ToolStripMenuItem();

at the start of the loop.

Iridium
  • 20,621
  • 6
  • 49
  • 68