Jump to content
  • Advertisement
Sign in to follow this  
violentcrayon

[C#] Probably a stupid error...

This topic is 3970 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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]

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!