Pergunta

For aggregating the number of occurences of some certain values, I'm using a dictionary<valueName:string, counter:int>, I don't know the values exactly. So I've written a method SetOrIncrement, which supposedly is used like

myDictionary.SetOrIncrement(name, 1);

However, there VisualStudio grumbls

"Dictionary does not contain a definition for 'SetOrIncrement' and no extension method 'SetOrIncrement' accepting a first argument of type 'Dictionary could be found."

Could anyone tell me what is the reason?

Here's the SetAndIncrement method:

public static class ExtensionMethods
{
    public static int SetOrIncrement<TKey, int>(this Dictionary<TKey, int> dict, TKey key, int set) {
        int value;
        if (!dict.TryGetValue(key, out value)) {
           dict.Add(key, set);
           return set;
        }
        dict[key] = ++value;
        return value;
    }
}
Foi útil?

Solução

Does your extension method compile correctly? When I try to compile it I get: "Type parameter declaration must be an identifier not a type".

The reason is that in this line:

public static int SetOrIncrement<TKey, int>(this Dictionary<TKey, int> dict, TKey key, int set) {

the int in the generic parameters for the method is not valid. Instead this should work:

public static int SetOrIncrement<TKey>(this Dictionary<TKey, int> dict, TKey key, int set) {

The reason being that TKey is the only type that varies. The int is always the same so isn't a generic parameter.

Outras dicas

Try this:

void Main()
{
    var dict = new Dictionary<string, int>();
    dict.SetOrIncrement("qwe", 1);
}

// Define other methods and classes here
public static class ExtensionMethods
{
    public static int SetOrIncrement<TKey>(this Dictionary<TKey, int> dict, TKey key, int set)
    {
        int value;
        if (!dict.TryGetValue(key, out value)) {
           dict.Add(key, set);
           return set;
        }
        dict[key] = ++value;
        return value;
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top