tags:

views:

213

answers:

1

I'm getting a "cannot convert from 'int' to 'TValue'" in the following code. How can I fix this? I understand why there is an issue, but I'm wonder the best way around this. Do I need to make a decision to specific type the ReturnValuesDict, and not leave it generic?

public class ReturnValuesDict<TKey, TValue> : CloneableDictionary<TKey, TValue>
{

    public static ReturnValuesDict<TKey, TValue> CreateEmptyClone(ReturnValuesDict<TKey, TValue> current) 
    {
        var newItem = new ReturnValuesDict<TKey, TValue>();
        foreach (var curr in current)
        {
            newItem.Add(curr.Key, 0);  // ERROR on the 2nd parameter here
        }
        return newItem;
    }

}
+12  A: 

The reason this does not compile is that 0 (an int) cannot, in general, be converted to the dictionary-values' type (TValue), which, as far as the compiler is concerned, is some arbitrary type. (where TValue : int wouldn't work, but that's another matter)

I assume you're trying to construct a dictionary with the same keys as the original, but with 'empty' values?

If you are ok with what .NET considers to be the 'default' value of a type, you could try changing the line to:

newItem.Add(curr.Key, default(TValue));  

This will use the default-value of the dictionary-values' type. For example:null for reference-types, zero for numeric-value types.

If, on the other hand, the intention is to write a method that only works with dictionarys having intvalues, you could make it more restrictive (place this in another class):

public static ReturnValuesDict<TKey, int> CreateEmptyClone<TKey>(ReturnValuesDict<TKey, int> current) 
{
    var newItem = new ReturnValuesDict<TKey, int>();
    foreach (var curr in current)
    {
        newItem.Add(curr.Key, 0);  
    }
    return newItem;
}

Note that the method is now a generic method that takes an unconstrained genericTKeyparameter.

Ani
Or if he wants, he can use `null` instead of 0 (which I think is his intention), provided the `TValue` is reference type. He can use `where` clause to state that.
Nayan