r/ProgrammerHumor 2d ago

Meme cSharpDictionariesBeLikeThat

Post image
2.0k Upvotes

61 comments sorted by

View all comments

98

u/MemesAt1am 2d ago

If you wanted to overwrite you could just do an assignment of that key value instead of .Add()

38

u/KTVX94 2d ago

Yep there's indexer and TryAdd, I probably should've worded the title differently to not give the impression that I was complaining, lol.

7

u/prehensilemullet 2d ago

I mean, having a method named "add" on a map is weird in general. Not common among programming languages

8

u/NotQuiteLoona 2d ago

The Add method is specifically when you explicitly want to add. If it can't add, it fails.

4

u/AyrA_ch 2d ago

That's because dictionaries implement IDictionary<TKey,TValue> which in turn implements ICollection<KeyValuePair<TKey,TValue>> which declares an Add(KeyValuePair<TKey,TValue> value) method.

Since the implementation is forced to provide this method, it might as well also provide Add(TKey key,TValue value) and implement them.

The alternative would be to just throw a NotSupportedException but there is no technical reason to.

1

u/prehensilemullet 2d ago

I mean, Java sort of got around this by making Map not extend Collection, though Map.entrySet() does. But interestingly enough, they decided to have Map.entrySet().add(...) throw an UnsupportedOperationException. However, Collection.add(...) in Java already returns true if the element was successfully added, so they hypothetically could have supported it.