1
votes

In an attempt to clean up a lot of repeated code, I tried implementing the extension method below:

    public static void AddIfNotPresent(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
    {
        if (!dictionary.ContainsKey(key))
        {
            dictionary.Add(key, value);
        }
    }

    public static void Test()
    {
        IDictionary<string, string> test = new Dictionary<string, string>();
        test.AddIfNotPresent("hi", "mom");
    }

Results in a compiler error during the extension method call of:

The type arguments for method 'Util.Test.AddIfNotPresent(this System.Collections.Generic.IDictionary dictionary, TKey key, TValue value)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Any light on this subject would be much appreciated!

3
Thanks guys, I'm a little wet around the ears about generics obviously. The compiler warning was really confusing me, I would have thought that the method itself would not compile (rather than compiler warnings being on the call). Thanks again - user195604

3 Answers

6
votes

Your extension method isn't generic, but should be, as extension methods must be defined in non-generic top level classes. Here's the same code after I've made it a generic method:

// Note the type parameters after the method name
public static void AddIfNotPresent<TKey, TValue>
    (this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
    if (!dictionary.ContainsKey(key))
    {
        dictionary.Add(key, value);
    }
}

However, trying to compile the code you actually posted gives a different error message from the one you specified. That suggests that you haven't posted the real code... and so the above may not fix things anyway. However, the code you posted with the above change works fine.

5
votes

Can't this be done simply with this?

dictionary[key] = value;

It adds the key/value pair if the key doesn't exist, or updates the value if it does. See Dictionary<TKey,TValue>.Item.

4
votes

Try this:

public static void AddIfNotPresent<TKey, TValue>
       (this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)    
{       
    if (!dictionary.ContainsKey(key)) dictionary.Add(key, value);
}   

public static void Test()    
{        
     IDictionary<string, string> test = new Dictionary<string, string>(); 
     test.AddIfNotPresent("hi", "mom");    
}