Deep copying data from class instances
Is there something that can generically and efficiently deep copy all of the data from one instance of a class into another already existing instance?
11 Replies
deepcopying usually happens in one of the three ways
-dedicated method and recursive calling
-serializing/deserializing
-reflection
this sounds like a mapping function. Or are you look for something that knows nothing about your class?
depending on usecase you might also consider using valuetypes
doesnt have to be mapping there are couple usecases where you want a second instance
Yeah I don't want to have to implement it per class. I guess serializing and deserializing will work. I just need a serializer that supports deserializing into existing instances all the way down the type tree
Most folks end up with some form of serialization. What makes you think you won't find a serializer that supports this?
Nothing, I'm just not aware of one / never tested it. I have to experiment and find one
Just use system.Text.json
System.Text.Json Namespace
Provides high-performance, low-allocating, and standards-compliant capabilities to process JavaScript Object Notation (JSON), which includes serializing objects to JSON text and deserializing JSON text to objects, with UTF-8 support built-in. It also provides types to read and write JSON text encoded as UTF-8, and to create an in-memory document...
This is my deep copy, would it work for you?
public static T DeepCopy<T>(this T obj)
{
var json = JsonSerializer.Serialize(obj);
return JsonSerializer.Deserialize<T>(json);
}
Something similar probably, I need to deserialize into existing instance of the type
I got it working with MemoryPack.
i've implemented deep copy implementations using code generators + attributes as markers ( as well as deep compare )