Question

I am trying to search through a dictionary with TryGetValue using an object as a key. I have overridden the GetHashCode which I thought would be what was required to set how the key is generated for a dictionary. The Item class below is the key for the dictionary.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;

public class Item : MonoBehaviour
{
   int id;
   string name;
   string itemType;

   public Item(string name, int id, string itemType)
   {
       this.name = name;
       this.id = id;
       this.itemType = itemType;
   }
   public override bool Equals(object obj)
   {
       if (obj == null)
        return false;
       Item myItem = (Item)obj;
       if (myItem == null)
        return false;

       return (name == myItem.name) && (itemType == myItem.itemType);
   }
   public override int GetHashCode()
   {        
       return (this.name + this.itemType).GetHashCode();
   } 
      [...]
   }

From a different class I use 'TryGetValue(Item,GameObject)' to see if the item exists in the dictionary but even when there are multiple Item's in the dictionary with the same name and itemType, it does not find the key.

public void UIItemCreate(Item item, GameObject itemGameObject)
{
    GameObject go = null;

    uiItemDictionary.TryGetValue (item, out go); 
    if(go == null)
    { 
     uiItemDictionary.Add(item,itemGameObject);
     go = NGUITools.AddChild(this.gameObject,itemGameObject);
    }
  [...]
}

Any suggestions? Is there something else I need to override?

Thanks,

Chris

Was it helpful?

Solution

Try overriding Equals as such:

public override bool Equals(object obj)
{
    var myItem = obj as Item;
    return !ReferenceEquals(myItem, null) && Equals(myItem);
}

public bool Equals(Item myItem)
{
    return string.Equals(name, myItem.name, StringComparison.Ordinal) && string.Equals(itemType, myItem.itemType, StringComparison.Ordinal);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top