Bug 16990

Summary: ConcurrentDictionary lacks proper support for Contains(KeyValuePair<TKey, TValue>)
Product: [Mono] Class Libraries Reporter: Adam Christie <fractos>
Component: mscorlibAssignee: marcos.henrich
Status: RESOLVED FIXED    
Severity: normal CC: marcos.henrich, mono-bugs+mono
Priority: ---    
Version: 3.2.x   
Target Milestone: Untriaged   
Hardware: PC   
OS: Linux   
Tags: Is this bug a regression?: ---
Last known good build:

Description Adam Christie 2013-12-30 09:38:03 UTC
While porting a Conclave (https://github.com/guy-murphy/Conclave) based application to run under Mono-3.x, I noticed a difference in behaviour for one of the enumeration functions based on a ConcurrentDictionary:

Mono implementation from ConcurrentDictionary.cs:

        bool ICollection<KeyValuePair<TKey,TValue>>.Contains (KeyValuePair<TKey, TValue> pair)
        {
             return ContainsKey (pair.Key);
        }

Expected implementation (from dotnetframework.org):

        bool ICollection<keyvaluepair<tkey, tvalue="">>.Contains(KeyValuePair<tkey, tvalue=""> keyValuePair)
        {
            TValue value;
            if (!TryGetValue(keyValuePair.Key, out value))
            {
                return false;
            }
            return EqualityComparer<tvalue>.Default.Equals(value, keyValuePair.Value);
        }

This difference means that when a KeyValuePair is submitted to Contains, then it will return True if just the key exists in the concurrent dictionary, instead of checking both whether the key exists and then checking the equality of the value.

I am using it in the following context:

        IEnumerable<KeyValuePair<string, string>> matchingAllParameters =
               new ImmutableDictionary<string, string>(new Dictionary<string, string> { { "action", "true" } });

        ConcurrentDictionary<string, string> parameters = new ConcurrentDictionary<string, string>
               { { "action", "false" } };

        bool matched = matchingAllParameters.All(p => parameters.Contains(p));

on Windows, matched will be false.
on Mono, matched will be true.

Current work around is:

        bool matched = matchingAllParameters.All(p => context.Params.Keys.Contains(p.Key) && context.Params[p.Key] == p.Value);
Comment 1 marcos.henrich 2014-05-30 06:47:00 UTC
Hi Adam,

Thank you for the detailed bug report.

The pull request for this issue can be found in the link below.
https://github.com/mono/mono/pull/1069
Comment 2 marcos.henrich 2014-05-30 09:18:21 UTC
Fixed in master db71dba1b775009146a9edaa1ac42abc4c0aaceb.