Tanveer’s Weblog

C++/CLI: Object Clone

May 8, 2009 · Leave a Comment

Basically, Clone can be implemented either as a deep copy or a shallow copy. In a deep copy, all objects are duplicated; whereas, in a shallow copy, only the top-level objects are duplicated and the lower levels containreferences.

But here we work under System::Runtime::Serialization::Formatters::Binary

Step 1: Serialize your object
Step 2: And then Deserialize  your object
Step 3: Close you MemoryStream instance
Step 4: Return Object
That’s it..

So here is the method,

public: System::Object^ Clone(System::Object^ apObj )
{
MemoryStream^ ms = gcnew MemoryStream();
BinaryFormatter^ bf = gcnew BinaryFormatter();
bf->Serialize( ms, apObj );
ms->Position = 0;
System::Object^ obj = bf->Deserialize( ms );
ms->Close();
return obj;
}

This is most fast way to clone your object very easily. So fulks ..

enjoy ;)

Categories: .NET · C++/CLI · Tips' n Tricks'

0 responses so far ↓

  • There are no comments yet...Kick things off by filling out the form below.

Leave a Comment