0

Is approach below thread safe? I know ConcurrentDictionary provides TryRemove method but I just don't like to have a variable for value that I never gonna use.

ConcurrentDictionary<int, int> myDict = new ConcurrentDictionary<int, int>();

if (myDict.ContainsKey(1))
    ((IDictionary<int, int>)myDict).Remove(1);
whoami
  • 1,689
  • 3
  • 22
  • 45
  • 5
    TryRemove is exposed for a reason. – David L Feb 06 '15 at 20:45
  • 1
    That is a silly argument. TryRemove is the safest way to access your data. You will get a return of True/False from it which let's you know if you should process the out variable. – phillip Feb 06 '15 at 20:46
  • If you really don't like having the variable laying around after TryRemove, then just scope it so it is only valid for that call. – Katie Feb 06 '15 at 20:50
  • @Katie That's possible, but fairly cumbersome in C#. – Servy Feb 06 '15 at 21:26
  • Why do you ignoring value stored in dictionary? If answer is "I already read it.", then very likely that your code is not thread safe. – user4003407 Feb 07 '15 at 01:34

1 Answers1

4

Your aim seems to be to improve code clarity by removing the need to use an out parameter. That is a valid concern but using Remove is not the right way to go.

Define yourself a helper method:

static bool TryRemove<TKey, Value>(
      this ConcurrentDictionary<TKey, Value> dict, TKey key) {
 TValue value;
 return dict.TryRemove(key, out value);
}
usr
  • 168,620
  • 35
  • 240
  • 369