Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Hashset Contains Non-Unique Objects

Tags:

c#

hashset

Using this class

public class Foo
{
    public string c1, c2;

    public Foo(string one, string two)
    {
        c1 = one;
        c2 = two;
    }

    public override int GetHashCode()
    {
        return (c1 + c2).GetHashCode();
    }
}

And this HashSet

HashSet<Foo> aFoos = new HashSet<Foo>();
Foo aFoo = new Foo("a", "b");

aFoos.Add(aFoo);
aFoos.Add(new Foo("a", "b"));

label1.Text = aFoos.Count().ToString();

I get the answer 2, when surely it should be 1. Is there a way to fix this so my HashSet contains only unique objects?

Thanks, Ash.

like image 311
Ash Avatar asked Jan 04 '11 21:01

Ash


2 Answers

The HashSet<T> type ultamitely uses equality to determine whether 2 objects are equal or not. In the type Foo you have only overridden GetHashCode and not equality. This means equality checks will default back to Object.Equals which uses reference equality. This explains why you see multiple items in the HashSet<Foo>.

To fix this you will need to override Equals in the Foo type.

public override bool Equals(object obj) { 
  var other = obj as Foo;
  if (other == null) {
    return false;
  }
  return c1 == other.c1 && c2 == other.c2;
}
like image 197
JaredPar Avatar answered Oct 13 '22 14:10

JaredPar


You need to override Equals method. Only GetHashCode is not enough.

like image 22
Victor Haydin Avatar answered Oct 13 '22 12:10

Victor Haydin