[Solved] How to make a deep copy Dictionary template


You can use Generics with where TValue : ICloneable constraint:

public static Dictionary<TKey, TValue> deepCopyDic<TKey, TValue>(Dictionary<TKey, TValue> src)
    where TValue : ICloneable
{
    //Copies a dictionary with all of its elements
    //RETURN:
    //      = Dictionary copy
    Dictionary<TKey, TValue> dic = new Dictionary<TKey, TValue>();
    foreach (var item in src)
    {
        dic.Add(item.Key, (TValue)item.Value.Clone());
    }

    return dic;
}

You’ll have to implement ICloneable interface in every class you’d like to pass into that method.

Or a bit improved version, with Key cloned as well:

public static Dictionary<TKey, TValue> deepCopyDic<TKey, TValue>(Dictionary<TKey, TValue> src)
    where TValue : ICloneable
    where TKey : ICloneable
{
    return src.ToDictionary(i => (TKey)i.Key.Clone(), i => (TValue)i.Value.Clone());
}

29

solved How to make a deep copy Dictionary template