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!
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:
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.