[C#] Probably a stupid error...

Started by
1 comment, last by tufflax 16 years, 9 months ago
Wow. I seem to be having a lot of questions. Hmm. Well, it's been a great learning experience. But...

public void InvetoryTest()
        {
            HP = 5;
            HealingItem heal = new HealingItem();
            HarmfulItem harm = new HarmfulItem();
            Item[] inventory = { heal, harm };                                  
            int itemValue;
            
            object itemType = harm;
            itemValue = Array.BinarySearch(inventory, itemType);                
                
            Console.WriteLine(HP);
            Item itemName = (Item)inventory.GetValue(itemValue);
            itemName.ApplyItem();
            Console.WriteLine(HP);            
            Console.ReadLine();
        }


So running that code (with other relevant methods), I get the following error:
Failed to compare two elements in the array. {/quote] If I change itemType to heal, then there's no error. If I switch the position of harm and heal, putting harm at 0 and heal at 1 and leave itemType as harm, it works. But if, after switching them, I make itemType heal, it breaks again. Basically, if itemType is the item at 0, I get that error. If I try to put NULL in the array, either at the beginning or end of it, then things are reversed. If itemType is the item at 1, it breaks. It's really quite boggling. What am I missing? [edit] If I don't have the variables declared in that block, it's because they're declared elsewhere, outside the method. [/edit]
http://neolithic.exofire.net
Advertisement
For BinarySearch to work, the items in the array need to implement the IComparable interface, and your classes do not.

The reason that it still sometimes works is (and this is just my guess) that binary search first does a regular comparison between the items (using object.Equals or operator==), which works in this case (but not always) because the first item it checks is the item you're looking for, and so it returns immediatly. If, however, the items are not equal, than it needs to call the CompareTo() function that IComparable requires to implement, and your classes don't have such a function.

So, in short, implement the IComparable interface and it should work.
You also need to sort them with Array.Sort before using BinarySearch.

This topic is closed to new replies.

Advertisement