views:

95

answers:

2

Why is the following 'exist' boolean variable getting a value of false???

foreach (Cell existCell in this.decoratorByCell.Keys)
{   
            //this call yield the same hashcode for both cells. still exist==false
            bool exist =
                this.decoratorByCell.ContainsKey(existCell);
}

I've overridden GetHashCode() & Equals() Methods as follows:

public override int GetHashCode()
{
            string nodePath = GetNodePath();

            return nodePath.GetHashCode() + m_ownerColumn.GetHashCode();
}

public bool Equals(Cell other)
{
bool nodesEqual = (other.OwnerNode == null && this.OwnerNode == null) || (other.GetNodePath() == this.GetNodePath());
bool columnsEqual = (other.OwnerColumn == null && this.OwnerColumn == null) || (other.OwnerColumn == this.OwnerColumn);
bool treesEqual = (this.m_ownerTree == other.m_ownerTree);

return (nodesEqual && columnsEqual && treesEqual);
}
+2  A: 

Your Equals and GetHashCode implementations do very different things. They should be mirroring each other.

You have no mention in GetHashCode to the m_ownerTree that you are using in your Equals implementation.

Also, adding up hashcodes is not the bast way of computing a hash. You may want to xor them (^) up.

Oded
+1  A: 

A hash algorithm must have the following property:

  • if two things are equal then they have the same hash

A hash algorithm should have the following properties:

  • changing a mutable object does not change its hash code
  • fast
  • never throw an exception
  • small differences between objects should cause large (ideally 50% of the bits) differences in hash code

Does your hash algorithm have the first, necessary property? It doesn't look to me like it does.

Eric Lippert
The .NET Framework documentation actually has a better description of what it must do and also clarifies your #1 should-do case: http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx
jasonh