Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom class inside HashSet<>

Tags:

c#

hashset

I would like to use HashSet<> in order to store large quantities (50-100) of a certain custom class, lets call it "Poster." As far as I know there is some performance benefit in using HashSet<> for large number of items over List<>. But in order to take advantage of this performance gain, do I "need" to define both of these?

  • public bool Equals(Poster a, Poster b)
  • public int GetHashCode(Poster obj)

UPDATE: For anyone looking on how to implement these, this is how I've done it:

public bool Equals(PosterImage a, PosterImage b)
{
    return (a.ApiId == b.ApiId);
}

public int GetHashCode(PosterImage obj)
{
    return ((PosterImage) obj).ApiId.GetHashCode();
}
like image 235
IKnowledge Avatar asked Feb 20 '26 18:02

IKnowledge


1 Answers

Yes, if you implement a IEqualityComparer<Poster>, you need to implement these methods. You will need to pass the equality comparer to the HashSet<Poster> constructor.

Another option is to implement the equality/hashcode logic in the Poster class itself; in this case you must override these methods:

public bool Equals(object obj)
public int GetHashCode()
like image 150
Thomas Levesque Avatar answered Feb 23 '26 07:02

Thomas Levesque