Jump to content
  • Advertisement
Sign in to follow this  

[C#] Probably a stupid error...

This topic is 4118 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);                
            Item itemName = (Item)inventory.GetValue(itemValue);

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
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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!