DeepCloner icon indicating copy to clipboard operation
DeepCloner copied to clipboard

Can't clone dictionary

Open kakkamstrup opened this issue 1 year ago • 4 comments

Here is a piece of code to recreate the bug, I hope.

using System.Collections.Generic; using System.Linq; using Force.DeepCloner;

namespace DeepClonerBug { internal class Program { static void Main(string[] args) { var org = new Dictionary<Location, Location[]> { { new Location { Name = "A" }, new[] { new Location { Name = "1" } } } };

        org[org.Keys.First()].ToString();

        var clone = org.DeepClone();

        // throws System.Collections.Generic.KeyNotFoundException: 'The given key was not present in the dictionary.'
        clone[clone.Keys.First()].ToString();
    }
}

public class Location
{
    public string Name { get; set; }
}

}

kakkamstrup avatar Jun 26 '23 05:06 kakkamstrup

Here is another example with HashSet. I guess they have the same root cause

using System; using System.Collections.Generic; using System.Linq; using Force.DeepCloner;

namespace DeepClonerBug { internal class Program { static void Main(string[] args) { var org = new HashSet<Location> { new Location() }; if (!org.Contains(org.First())) throw new Exception();

        var clone = org.DeepClone();
        //uncomment to fix:  clone = new HashSet<Location>(clone.ToList());

        if (!clone.Contains(clone.First())) throw new Exception();
    }
}

public class Location
{
}

}

kakkamstrup avatar Jun 26 '23 08:06 kakkamstrup

You need to override GetHashCode and Equals methods for Location class. It bad idea to add to dictionary objects without overriding these methods. It can cause issue in any situation

set.Add(new Location { Name = "A" });
set.Contains(new Location { Name = "A" }) // false

I know this issue but I do not found ways how to correctly bypass it. I can make some hotfixes for Dictionary and HashSet, but there are lot of another classes, with using these methods (e.g. ConcurrentDictionary, or LINQ method Distinct which creates specific internal HashSet).

force-net avatar Jun 26 '23 11:06 force-net

OK, thank you for your reply. I can make it work with overriding GetHashCode and Equals.

Maybe this is not the right place to ask. I want to clone the same object multiple times, is there a way to speed up performance for this case?

kakkamstrup avatar Jun 26 '23 12:06 kakkamstrup

I want to clone the same object multiple times Code is optimized, so there are no sense to add special method for this (it will be complex with internal state). I'll think about this. May be I found way to do this method simple and self-descriptive.

force-net avatar Jun 26 '23 14:06 force-net