How to handle a generic dictionary whose types are unknown and don't matter?

c#, dictionary, generics

Solution

Make your method generic as well and then you'll be able to do what you're doing. You won't have to change your usage pattern since the compiler will be able to infer generic types from input types.

public IDictionary<object, object> Copy(IDictionary<TKey, TValue> source)
{

    IDictionary<object,object> targetDictionary = new Dictionary<object,object>();

    foreach (KeyValuePair<TKey, TValue> sourcePair in sourceDictionary)
    {
         targetDictionary.Insert(sourcePair.Key, sourcePair.Value);
    }

    return targetDictionary; 
}

If you don't really need to convert it from `IDictionary<TKey, TValue>` to `IDictionary<object, object>` then you can use the copy constuctor of `Dictionary<TKey, TValue>` which accepts another dictionary as input and copies all values--just like you're doing now.

Problem

If 'value' is an incoming generic dictionary whose types are unknown/don't matter, how do I take its entries and put them into a target dictionary of type `IDictionary<object, object>` ? ``` if(type == typeof(IDictionary<,>)) { // this doesn't compile // value is passed into the method as object and must be cast IDictionary<,> sourceDictionary = (IDictionary<,>)value; IDictionary<object,object> targetDictionary = new Dictionary<object,object>(); // this doesn't compile foreach (KeyValuePair<,> sourcePair in sourceDictionary) { targetDictionary.Insert(sourcePair.Key, sourcePair.Value); } return targetDictionary; } ``` EDIT: Thanks for the responses so far. The problem here is that the argument to Copy is only known as type 'object'. For example: ``` public void CopyCaller(object obj) { if(obj.GetType() == typeof(IDictionary<,>) Copy(dictObj); // this doesn't compile } ```

Original source