C# memcpy equivalent

Adi Barda picture Adi Barda · Feb 4, 2009 · Viewed 13.8k times · Source

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?

Answer

Quassnoi picture Quassnoi · Feb 4, 2009

In C# (and in C++ too), there is no difference between "new object" and "a copy of existing object" as long as all their members equal to each other.

Given:

Int32 a = 5;

, both operations:

Int32 b = 5;
Int32 b = a;

yield the same result.

As stated in MSDN reference:

The MemberwiseClone method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object.

If a field is a value type, a bit-by-bit copy of the field is performed.

If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.

, i.e. it does just the same as memcpy() in C++