I want to make arithmetic operations between dictionaries with numbers as value. This is my code:
public class DictionaryOperation {
public static Dictionary<TKey, double> Add<TKey>(Dictionary<TKey, double> d1, Dictionary<TKey, double> d2) {
Dictionary<TKey, double> result = new Dictionary<TKey, double>();
foreach (TKey key in d1.Keys) {
if (d2.ContainsKey(key))
result[key] = d1[key] + d2[key];
else
result[key] = d1[key];
}
foreach (TKey key in d2.Keys) {
if (!result.ContainsKey(key))
result[key] = d2[key];
}
return result;
}
}
I would like to know if I can create only one method for any numeric type (int float, decimal, ...) or do I have to create one method per numeric type, which means there will be the same code in each methods.
I want to be able to do this:
Dictionary<string, int> ints = DictionaryOperation.Add(new Dictionary<string, int>(), new Dictionary<string, int>());
Dictionary<string, float> floats = DictionaryOperation.Add(new Dictionary<string, float>(), new Dictionary<string, float>());