Failed to compare two elements in array

private SortedList<ToolStripMenuItem, Form> forms = new SortedList<ToolStripMenuItem, Form>(); private void MainForm_Load(object sender, EventArgs e) { formsAdd(menuCommandPrompt, new CommandPrompt()); formsAdd(menuLogScreen, new LogScreen()); //Error } private void formsAdd(ToolStripMenuItem item, Form form) { forms.Add(item, form); //Failed to compare two elements in the array. form.Tag = this; form.Owner = this; } 

I cannot understand why this is causing the error. The error occurs in the second line of the form load event.

The formsAdd method simply adds the form element and toolstip to the array (s) and sets the tag and form owner for this. The second time the function is called, it throws an error.

 CommandPrompt, LogScreen /* are */ Form //s menuCommandPrompt, menuLogScreen /* are */ ToolStripMenuItem //s 

Error

+4
source share
2 answers

You have a SortedList , but ToolStripMenuItem does not implement IComparable , so the list does not know how to sort them.

If you don't need to sort the items, you can use the Tuple or Dictionary list, depending on what exactly you want to do.

If you want them to be sorted, you need to use the overload of the SortedLists constructor , which accepts IComparer . This means that you must somehow implement this interface.

+10
source

Are both types of IComparable objects provided? This is necessary for a sorted list to compare the objects that it adds to the array.

+2
source

All Articles