Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

314
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!