HashSet allows duplicate item insertion - C#

jpints14 picture jpints14 · Jan 5, 2012 · Viewed 38.8k times · Source

This kind of seems like a noob question, but I could not find an answer for this question specifically.

I have this class:

public class Quotes{ 
    public string symbol; 
    public string extension
}

And am using this:

HashSet<Quotes> values = new HashSet<Quotes>();

However I am able to add the same Quotes object multiple times. For example, my Quotes object may have 'symbol' equal to 'A' and 'extension' equal to '=n', and this Quotes object appears multiple times in the HashSet (viewing Hashset through debug mode). I had thought that when calling

values.Add(new Quotes(symb, ext));

with the same symb and ext, 'false' would be returned and the element would not be added. I have a feeling it has something to do with comparing Quotes objects when the HashSet is adding a new object. Any help would be greatly appreciated!

Answer

Kendall Frey picture Kendall Frey · Jan 5, 2012

I'm guessing that you are creating a new Quotes with the same values. In this case they are not equal. If they should be considered equal, override the Equals and GetHashCode methods.

public class Quotes{ 
    public string symbol; 
    public string extension

    public override bool Equals(object obj)
    {
        Quotes q = obj as Quotes;
        return q != null && q.symbol == this.symbol && q.extension == this.Extension;
    }

    public override int GetHashCode()
    {
        return this.symbol.GetHashCode() ^ this.extension.GetHashCode();
    }
}