views:

157

answers:

3

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!

+4  A: 

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");    
}
Charles Bretana
+5  A: 

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.

Jon Skeet
+4  A: 

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.

Lucas
+1 for pointing out the simple usage of `IDictionary`. Though the question is more about why something doesn't compile, and less about proper usage of `IDictionary`
Nader Shirazie