Domanda

I'm building a menu in my WinForm app and i was doing something like :

MenuItem[] items = new MenuItem[] { };

And after :

for (int namesIndex = 0; namesIndex < menuNames.Length; namesIndex++)
{
    MenuItem item = new MenuItem(menuNames[namesIndex]);

    for (int entriesIndex = 0; entriesIndex < menuEntries.GetLength(1); entriesIndex++)
    {
       item.MenuItems.Add(menuEntries[namesIndex, entriesIndex]);
    }

    items[namesIndex] = item;
}

And an IndeOutOfRangeException is thrown :

enter image description here

After this annoying exception i modified the array declaration with this :

 MenuItem[] items = new MenuItem[] { null };

and everything works like a charm.

And now the question : Does anyone out there knows why the above array declaration works, and the other doesn't? Thanks alot

È stato utile?

Soluzione

You're using array initializers to construct the array, so the length of the array will be given by the data you provide.

The first example declares an array with a length of zero as you don't provide any elements. I.e. it cannot contain any elements.

The second example declares an array of length one.

Altri suggerimenti

MenuItem[] items = new MenuItem[] { };

This creates an array with 0 items in it.

MenuItem[] items = new MenuItem[] { null };

This creates an array with 1 item in it (it's null, but that still counts).

You probably want to initialize for the number of items you want (new MenuItem[menuNames.Length], for example). Or use new List<MenuItem>() instead, and call Add().

"Everything works like a charm" only to the extent that menuNames has exactly one item. You need to change the code as follows to make it work:

MenuItem[] items = new MenuItem[menuNames.Length];

The reason you saw a crash in the first case is that you created an array with zero items, while in the second case you created an array with one item. If menuNames has more than one element, your code would start crashing again.

Your for loop iterates over compares the loop variable to menuNames.Length, while your using the indexer of the items array. One of the two is wrong.

Additionally, if you want to be adding additional items to a collection, then you should almost certainly be using a List, not an array.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top