Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

250
Vistas
Why is GetHashCode not called during Contains?

Until today my understanding was that a HashSet uses GetHashCode inside Contains. That is also said e.g. here.

I wrote a little IEqualityComparer:

public class MyComparer : IEqualityComparer<string>
{
    public bool Equals(string? a, string? b)
    {
        return a == b;
    }

    public int GetHashCode(string a)
    {
        throw new NotImplementedException();
    }
}

And used it like so:

public void TestMyComparer()
{
    var x = new HashSet<string>(new []{ "hello", "world" });
    bool helloInside = x.Contains("hello", new MyComparer());
}

But TestMyComparer does not throw a NotImplementedException, as I expected. Instead, it returns true.

Why?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

If you use HashSet.Contains pass your custom comparer to the constructor.

var x = new HashSet<string>(new MyComparer());
x.Add("hello");
x.Add("world");
bool helloInside = x.Contains("hello");

Now GetHashCode is used since you use a set based collection and not Enumerable.Contains which just enumerates all items and compares them with Equals.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda