ExceptWith in HashSet for complex types
c#, equals, hashset
Solution
When overriding `Equals` you should also override `GetHashCode`. `HashSet` (and other hashing structures like `Dictionary`) will first calculate a hash code for your objects to locate them in tne structure before comparing elements with `Equals`.
public override int GetHashCode()
{
return StringComparer.InvariantCulture.GetHashCode(this.Name);
}
Problem
I have HashSet of my custom class: ``` public class Vertex { public string Name; public override bool Equals(object obj) { var vert = obj as Vertex; if (vert !=null) { return Name.Equals(vert.Name, StringComparison.InvariantCulture); } return false; } } ``` And now I have tow hashsets ``` HashSet<Vertex> hashSet1 = new HashSet<Vertex>(); HashSet<Vertex> hashSet1 = new HashSet<Vertex>(); ``` And now I'd like to have in hashSet1 only Vertexes that are not in hashSet2 So I use ExceptWith method ``` hashSet1.ExceptWith(hashSet2); ``` But this doesn't work. I suppose that this doesn't work because I have complex type. So the question is: is there some interface required to be implemented in Vertex class to make this thing work? I know that while creation of HashSet I can pass a EqualityComparer but it seems to me that it would be more elegant to implement some comparing interface method in Vertex class. Is it possible or I just doesn't understand sth? Thanks.