Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failed to compare two elements in the array

Tags:

arrays

c#

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 can't get that why it throws error. Error occurs on second line of form load event.

formsAdd method simply adds form and toolstip element to the array(forms) and sets tag and owner of form to this. On second call of function, it throws an error.

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

Error

like image 420
haxxoromer Avatar asked Dec 17 '22 09:12

haxxoromer


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 have the items sorted, you can use a list of Tuples or a Dictionary, depending on what exactly do you want to do.

If you want to have them sorted, you need use the overload of SortedLists's constructor that takes IComparer. That means you have to implement that interface in some way.

like image 139
svick Avatar answered Jan 07 '23 07:01

svick


Do both your object types implement IComparable? This is a must for the sorted list to compare the objects it is adding to the array.

like image 41
Frazell Thomas Avatar answered Jan 07 '23 07:01

Frazell Thomas