✅ Is there something like MemberwiseCopy rather than MemberwiseClone?
I have a library I'm trying to keep AoT compatible. I have a class that users will extend for extra fields/properties for state that gets serialized. Because there will be hundreds of theses objects created and discarded per second, they're pooled. To make things more complicated, the system often needs to shallow copy them.
MemberwiseClone()
seems to work great for this since you can define it in the base class and all inherited types can use it. This would be the answer and I'd be done, but it allocates a clone rather than copies to a provided pooled object. Is there a similar way to do this while remaining AoT compatible?
My other option is to rewrite the system to not be extended and instead configured with some complex struct setup for the user's state, but I'd rather not have to explore that route if I need to.7 Replies
You could probably take a look at the implementation and base a
MemberwiseCopy
method on that
https://github.com/dotnet/runtime/blob/1d1bf92fcf43aa6981804dc53c5174445069c9e4/src/coreclr/System.Private.CoreLib/src/System/Object.CoreCLR.cs#L22C13-L35C26Unfortunately, it looks like all those methods are part of CoreCLR and can't be used. 🫠
Or, if there is a way to do that, I haven't gone deep enough in unsafe territory to know how.
There's
Unsafe.Copy()
maybe?
https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.unsafe.copy?view=net-9.0Hm. That requires knowing the inherited type when calling, so the user would have to override it for every class.
MemberwiseClone()
seems to just be special and zags around that requirement.Only thing that comes to mind would be a source generator
But pretty sure it can be done with some
unsafe
code regardless
People in #allow-unsafe-blocks would have a better idea. Link this thread in that channel maybeYeah, I'd rather an unsafe method than to include a source gen project, I'll reach out. Thanks!
According to them it's just a limitation of C# and
MemberwiseClone()
is something that shouldn't really be used in the first place and is only there for legacy reasons or something, so an overload that takes an object wouldn't ever be planned. Good knowledge to have! I'll think of a new system.A source generator is probably the best way to go, then