Search code examples
c#serializationcopying

C# memcpy equivalent


I have 2 objects from the same type and i would like to shallow copy one state to the other. In C++ i have memcpy which is great. How can i do it in C#? The MemberwiseClone() is not good enough because it creates & returns a new object and i like to copy to an existing object. I thought of using reflection but i'm afraid it will be too slow for production code. I also thought of using one of the .Net serializers but i think they also create object rather than setting an existing one.

My Use Case:

I have a template object (class not struct) which needs to be updated by one of its instances (objects made of this template)

Any ideas?


Solution

  • [edit] regarding your clarification: As I understand, you have N objects, each has a (direct) reference to the template object. You want to write back to the template so all objects "see" these changes.

    Suggestion: imlement a template broker.

    class TemplateProvider
    {
       public MyData Template { get; set; }
    }
    

    Instead of passing the template, pass the template provider to the objects.

    to simplyfy the syntax in the components, you can add a (private/internal?) property

    MyData Template { get { return m_templateProvider.Template; } }
    void UpdateTemplate() { m_templateProvider.Template = 
                                (MyData) this.MemberwiseClone(); }
    

    The template provider also simplifies locking in multithreaded scenarios.


    In short, no way unless you do it yourself. But why not create a new object if you override all properties anyway?

    memcopy and similar low level constructs are not supported since they undermine guarantees made by the environment.

    A shallow copy for structs is made by assignment. For classes, MemberwiseClone is the method to do that - but as you say that creates a new object.

    There is no built in way for that, and as it potentially breaks encapsulation it should be used with care anyway.

    You could build a generic routine using reflection, but whether it works or not depends on the class itself. And yes, ti will be comparedly slow.

    What's left is supporting it by a custom interface. You can provide a generic "Shallow Copy" routine that checks for the interface and uses that, and falls back to reflection when it doesn't. This makes the functionality available generally, and you can optimize the classes for which performance matters later.