Matt Frear
Matt Frear

Reputation: 54831

Addition (i.e. +) extension method with a generic C# Dictionary

I'm trying to write a generic Dictionary extension method like so. TValue will always be an int but TKey could be a string or a DateTime.

public static void AddOrIncrement<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value) 
{
    if (!dict.ContainsKey(key))
    {
        dict.Add(key, value);
    }
    else
    {
        dict[key] += value;
    }
}

But this won't compile - Operator '+=' cannot be applied to operands of type 'TValue' and 'TValue'.

So then I try:

public static void AddOrIncrement<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value) where TValue : int

but that doesn't compile either. So then I tried:

public static void AddOrIncrement<TKey, int>(this Dictionary<TKey, int> dict, TKey key, int value)

which doesn't compile - "Type parameter declaration must be an identifier not a type"

Upvotes: 0

Views: 579

Answers (2)

SLaks
SLaks

Reputation: 887469

You're trying to make an extension method that takes only one generic parameter:

public static void AddOrIncrement<TKey>(this Dictionary<TKey, int> dict, TKey key, int value)

Upvotes: 4

MrKWatkins
MrKWatkins

Reputation: 2658

Try:

public static void AddOrIncrement<TKey>(this Dictionary<TKey, int> dict, TKey key, int value)

Upvotes: 4

Related Questions