The Equals ( object obj) method for HashSet Contains check is not behaving in expected manner and I am not able to root cause it. Any help will be appreciated.
I am using a C# HashSet to store class object POS. Have declared it as
public static HashSet Store = new HashSet();
On calling Store.Add (A) A is stored in the Hashset properly.
When i try Store.Contains(B) for the case when GetHasCode returns the same hascode for A and B, the Equals method is called. The problem I am facing is in the Equal method I never get invocation for obj A. It ways gives me obj B as reference and hence evaluates to true. Since the hascode for both A and B are same should Equals not be called with obj A as reference?
/* The class object to be entered in Hashset is given below */
public class POS
{
private int[] R = new int[Constants.MaxN];
public int prev;
/** Methods for the class goes here **/
/* To use enter the object in Hashset placed the GetHashCode and Equals functions below */
public override int GetHashCode()
{
uint val=0;
uint temp = 0;
int j = 0;
for (long i = 0; i < Globals.GetN(); i++)
{
if (i > 9) { break; }
temp = (uint)R[i];
j = (int)i * 3;
val |= (temp << j);
}
return (int) val;
}
public override bool Equals(object obj)
{
int temp, tmp;
var POSitem = obj as POS;
Console.WriteLine("Entered:");
if (obj == null) { return false; }
if (ReferenceEquals(this, POSitem)) return true;
for (int i = 0; i < Globals.GetN(); i++)
{
temp = this.Give(i);
tmp = POSitem.Give(i);
if (temp != tmp) return false;
}
return true;
}
} // end braces of POS