C
C#2w ago
Mr. Dink

✅ 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
Mr. Dink
Mr. DinkOP2w ago
Unfortunately, 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.
Mr. Dink
Mr. DinkOP2w ago
Hm. 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.
Angius
Angius2w ago
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 maybe
Mr. Dink
Mr. DinkOP2w ago
Yeah, 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.
Angius
Angius2w ago
A source generator is probably the best way to go, then

Did you find this page helpful?