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

320
Vistas
Why Dictionary Add method throws exception when key is already present but HashSet does not

I am trying to understand thought process behind this design decision. Also return type of Dictionary.Add is void. It would be nice to have same behavior for both data structures. Or is there any use case which makes current implementation a better choice?

The HashSet class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the Dictionary<TKey,TValue> or Hashtable collections. In simple terms, the HashSet class can be thought of as a Dictionary<TKey,TValue> collection without values.

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

0

I am trying to understand thought process behind this design decision

Only the person or people who actually made the decision can provide that. They are unlikely to see your question here, though of course that possibility can't be ruled out.

is there any use case which makes current implementation a better choice?

There are lots of use cases. But the main thing to keep in mind is that adding the same object to a set (like HashSet<T>) that is already in the set is non-destructive, while adding the same key to a dictionary (like Dictionary<TKey, TValue>) is destructive, i.e. it overwrites the existing value.

Having the Add() method return a bool like HashSet<T> does wouldn't be helpful; by the time you see the false value that's been returned, the old value for the key will have already been replaced.

That said, do note that the indexer for dictionaries will overwrite the existing value silently. So in fact, dictionaries have exactly the same functionality that HashSet<T>, plus the capability to prevent you from accidentally overwriting a value that's already been stored.

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