How can I use the memberwiseclone method in c#?
The method MemberwiseClone is applied to many collections like arraylist etc,how can I implement this method?also give an example?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Satyapriya NayakRank #47 · 31.5K reputationPosted Jul 1, 2012, 10:03 PM EDT
Please refer the below links
http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx
http://buttle.shangorilla.com/1.1/handlers/monodoc.ashx?link=M%3ASystem.Object.MemberwiseClone
Thanks
Jignesh TrivediRank #16 · 50.3K reputationPosted Jul 1, 2012, 11:08 PM EDT
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.
Please refer,
http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone%28v=vs.80%29.aspx
http://dotnetgurukul.com/2011/02/24/cloning-in-c-shallow-copy-using-memberwiseclone-method/
hope this will help u.
VulpesRank #55 · 29.2K reputationPosted Jul 2, 2012, 1:34 AM EDT
Notice that the integer field is deep copied as it's a value type.
Even though it's a reference type, the string field is also deep copied as it's immutable - when a change is made a new string object is created rather than the old one being changed.
However, the reference type (SomeClass) is shallow copied - when a change is made to SomeInt it's still part of the same object and so the change is reflected in the clone: