6 ms·
> but you'd still have to contend with OPC (Other People's Code) and if the language allows it, you just know it will turn up somewhere and ruin your day! ;) Y
by mercurial 10y ago
> but you'd still have to contend with OPC (Other People's Code) and if the language allows it, you just know it will turn up somewhere and ruin your day! ;)
Yes, like the standard library's Dictionary.TryGetValue()...
- yread 10y agoyou can do if (dict.ContainsKey(key)) return dict[key] else return null; the only place where you can't avoid them are TryParse. And there it sort of makes sense - the value is sort of side effect
- louthy 10y ago> if (dict.ContainsKey(key)) return dict[key] else return null; Which isn't thread-safe. So it's not always a better option.
- ygra 10y agoBut Dictionary<TKey,TValue> isn't thread-safe anyway, unless not modified.
- louthy 10y agoCalling TryGetValue will either return a value or not. Calling ContainsKey, followed by an index read can lead to a race condition that means the value isn't there any more.
- pmarreck 10y agoThis is correct (and unfortunate).
- ygra 10y agoIf I'm reading the source correctly you could still get the bucket index and before you return true and the value, have that value removed from the dictionary. There is no synchronization going on, so concurrent modifications are just as much a problem with TryGetValue as with other approaches. TryGetValue is not atomic either.
- louthy 10y agoOk, fair enough. My mistake. Glad I don't use the BCL collection types any more and stick to immutable maps, lists, and sets :)