I need to 'copy' an object. I tried using the IClonable interface, with no avail and the most sensable solution to me is to use unsafe code to create a pointer to the object and then write a method like Memcpy in C. The only problem is creating a pointer to a managed type. I am assuming that doing such will bring issues with the garbage collector, but if it is possible to use marshaling or something to create a pointer to a managed object then I could write a function like memcpy in C and just copy my object. If structs can be unmanaged then why can't objects? An object is essentially a struct pointer so in theory it should be equal to size of an IntPtr right?
1 Answer
I solved this on my own, for those who said my idea of using pointers, that comes from my background with C... Anyway using serialization this method did exactly what I needed.
public object Clone()
{
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, this);
ms.Position = 0;
return formatter.Deserialize(ms);
}
}
2 Comments
evanmcdonnal
This is a good solution to do a deep copy of a complex object.
Kirk Woll
@user, I'm glad you found a solution and circled-back to post it here. I've used this approach myself. However, the assumptions made in your question indicate you have a lot of misconceptions for how a managed language like C# (in the CLR -- or Java in the JVM) actually works. First and foremost, this notion that you could "memcopy" an object and arrive at a new one ignores the concept of garbage collection; how would the GC system know that it needs to eventually deallocate that memory? (and regardless, the CLR must know about all objects for the CLR to work at all)
IClonable.Clonemethod? Did you call yourClone()method? Are you trying to copy/pass a C# object over to a C program?IClonable, either way it doesn't matter. You'll have to write a method where you set every value in the new object to whatever it is in the old one.ICloneabledoes is that it makes you implement theClone()method. It's up to you if you implement it as shallow or deep cloning. I think it would help if you posted the code of your attempt and described how exactly did it not work.