dmarra
dmarra

Reputation: 863

Why can I not add null as a value when using ConcurrentDictionary?

Consider the following code:

// holds the actual values
        private volatile ConcurrentDictionary<string, Object> values;

        public object this[string key] {
            get {     
                // exception is thrown on this line          
                return values.GetOrAdd(key, null);                
            }
            set {
                values.AddOrUpdate(key, value, (k, v) => value);                
            }
        }

What I want to do is simply create the entry in the dictionary if it does not exist yet; it should have no value though until something explicitly sets it. I get this exception though:

An unhandled exception of type 'System.ArgumentNullException' occurred in mscorlib.dll

Additional information: Value cannot be null.

The documentation states that key cannot be null, which makes sense. why am I getting this exception for a value though? Am I not understanding this method?

Upvotes: 1

Views: 3119

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100545

Code ends up calling the other GetOrAdd that takes Func as argument (and it explicitly required not to be null - "key or valueFactory is null.").

public TValue GetOrAdd(TKey key,Func<TKey, TValue> valueFactory)...

Fix: specify type explicitly:

 values.GetOrAdd("test", (Object)null);

Why: C# always tries to find more specific match and Func<TKey, TValue> is more specific than Object - so that override is picked.

Upvotes: 4

Related Questions