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
ACiDCA7
ACiDCA75w ago
deepcopying usually happens in one of the three ways -dedicated method and recursive calling -serializing/deserializing -reflection
suuuuuuuper
suuuuuuuper5w ago
this sounds like a mapping function. Or are you look for something that knows nothing about your class?
ACiDCA7
ACiDCA75w ago
depending on usecase you might also consider using valuetypes doesnt have to be mapping there are couple usecases where you want a second instance
nathanAjacobs
nathanAjacobsOP5w ago
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
Mayor McCheese
Most folks end up with some form of serialization. What makes you think you won't find a serializer that supports this?
nathanAjacobs
nathanAjacobsOP5w ago
Nothing, I'm just not aware of one / never tested it. I have to experiment and find one
Mayor McCheese
Just use system.Text.json
Mayor McCheese
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...
suuuuuuuper
suuuuuuuper5w ago
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); }
nathanAjacobs
nathanAjacobsOP5w ago
Something similar probably, I need to deserialize into existing instance of the type I got it working with MemoryPack.
public static class OverwriteUtility
{
[ThreadStatic]
private static readonly ArrayBufferWriter<byte> buffer = new();

public static void Overwrite<T>(in T from, ref T to)
{
buffer.Clear();
MemoryPackSerializer.Serialize(buffer, from);
MemoryPackSerializer.Deserialize(buffer.WrittenSpan, ref to);
}
}
public static class OverwriteUtility
{
[ThreadStatic]
private static readonly ArrayBufferWriter<byte> buffer = new();

public static void Overwrite<T>(in T from, ref T to)
{
buffer.Clear();
MemoryPackSerializer.Serialize(buffer, from);
MemoryPackSerializer.Deserialize(buffer.WrittenSpan, ref to);
}
}
lordgufi
lordgufi5w ago
i've implemented deep copy implementations using code generators + attributes as markers ( as well as deep compare )
Want results from more Discord servers?
Add your server