Probably I miss something using a HashSet and HashCode, but I don´t know why this doesn't work as I thought. I have an object with the HashCode is overridden. I added the object to a HashSet and later I change a property (which is used to calculate the HashCode) then I can´t remove the object.
public class Test
{
public string Code { get; set; }
public override int GetHashCode()
{
return (Code==null)?0: Code.GetHashCode();
}
}
public void TestFunction()
{
var test = new Test();
System.Collections.Generic.HashSet<Test> hashSet = new System.Collections.Generic.HashSet<Test>();
hashSet.Add(test);
test.Code = "Change";
hashSet.Remove(test); //this doesn´t remove from the hashset
}
Firstly, you're overriding GetHashCode
but not overriding Equals
. Don't do that. They should always be overridden at the same time, in a consistent manner.
Next, you're right that changing an objects hash code will affect finding it in any hash-based data structures. After all, the first part of checking for the presence of a key in a hash-based structure is to find candidate equal values by quickly finding all existing entries with the same hash code. There's no way that the data structure can "know" that the hash code has been changed and update its own representation.
The documentation makes this clear:
You can override
GetHashCode
for immutable reference types. In general, for mutable reference types, you should overrideGetHashCode
only if:
- You can compute the hash code from fields that are not mutable; or
- You can ensure that the hash code of a mutable object does not change while the object is contained in a collection that relies on its hash code.
See more on this question at Stackoverflow