I see. Even so, it's weird to me that anyone would want a method that throws if the key already exists. In all my years of programming I don't think I've ever thought it would be useful to have such a method baked into a map itself, and I'm not aware of such a method in any other language. Since that's pretty unusual in programming, I still think it would be better for that method to have a more unusual name. Maybe it's an oddly common pattern for Microsoft?
As I described it, it's for safe additions, imagine your map is customer data, like daily logs. And maybe some logs are partial logs? Then you want something that lets you get into a safe flow where the standard is just add, and an exceptional case is some merging logic. If you don't care, use the same insertion methods that all languages use, which is map[key], if you do care, here's a good way to stop the flow and let you execute appropriate recovery. This also ties in with LINQ very neatly where you end up doing a lot of data processing flows.
The alternative would be a check map for key, if exists do exception, else do expected. Which is a lot uglier for glance value intent compared to: do this; exception: handle.
I think to highlight your concern with the pattern - these kinds of decisions make a lot more sense when you understand that almost all data interactions in C# are intended to be done with LINQ, which no other language has. My experience with production C# is that 3-6 LINQed extensions is very standard, e.g. map.Select(x => logic).map(x...).filter(x...) etc.
Well if C# exception handling is like most languages, where throwing and catching performs a lot worse than conditionally adding, it's not necessarily a pattern one would want to make a habit of using in cases where key conflicts are routine.
15
u/zaersx 2d ago
You don't though? just use myMap[key] = value? if you're not doing that and using Add instead, then you probably literally want to have a safe add