Sunday, May 24, 2009

ContainsKey problem

Hi,
In case that u have generic Dictionary with non primitive key - ContainsKey function will return u a bad answer because this function compare objects by refrence an NOT by value!
so, if u have same key values in the Dictionary and in your test object u will get negative answer.
the solution is 2 override Equals and GetHashCode functions:


//@@@ I have Dictionary with Key_Event5 object as the key
Dictionary<Key_Event5, Event5_Employment> dictEmployment;
//@@@ 4 support ContainsKey function compare by value, i'll implement Key_Event5 on this way:
public class Key_Event5
{
public int iFormID { get; set; }
public int iEmploymentCode { get; set; }
public Key_Event5(int iFormID, int iEmploymentCode)
{
this.iFormID = iFormID;
this.iEmploymentCode = iEmploymentCode;
}

public override bool Equals(object obj)
{
Key_Event5 oKey_Event5 = obj as Key_Event5;
if (oKey_Event5 == null)
return false;
//@@@ Compare by iFormID and iEmploymentCode
return Equals(iFormID, oKey_Event5.iFormID)
&& Equals(iEmploymentCode, oKey_Event5.iEmploymentCode);

}
public override int GetHashCode()
{
return iFormID.GetHashCode() ^ iEmploymentCode.GetHashCode();
}

}
//@@@ And now this line will work
dictEmployment.ContainsKey(oKey_Event5)

No comments: