Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashSet allows duplicate item insertion - C#

Tags:

c#

.net

hashset

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!

like image 581
jpints14 Avatar asked Jan 05 '12 18:01

jpints14


1 Answers

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();     } } 
like image 195
Kendall Frey Avatar answered Sep 30 '22 07:09

Kendall Frey