I have a Node class :
public class Node : INode
{
public object Value { get; set; }
}
And I have EqualityComparer for this Node class like this :
public class INodeEqualityComparer : EqualityComparer<INode>
{
private INodeEqualityComparer()
{
}
private static readonly INodeEqualityComparer _instance =
new INodeEqualityComparer();
public static INodeEqualityComparer Instance
{
get { return _instance; }
}
public override bool Equals(INode x, INode y)
{
return (int)(x.Value) == (int)(y.Value);
}
public override int GetHashCode(INode obj)
{
return ((int)(obj.Value)).GetHashCode();
}
}
I create my HashSet by passing the NodeEqualityComparer.
I have 4 Node instances :
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
Node n4 = new Node(1);
When I add n1,n2,n3,n4 to my hashset , n4 get ignored.
HashSet<INode> nodes = new HashSet<INode>(INodeEqualityComparer.Instance);
nodes.Add(n1);
nodes.Add(n2);
nodes.Add(n3);
nodes.Add(n4);
BUT after I use this changing :
nodes.Where(n => (int)(n.Value) == 3).FirstOrDefault().Value = 1;
there will be 2 elements that are equal together (value=1) based on NodeEqualityComparer. those are n1 and n3.
WHY the hashset does not prevent updating node or remove it ?