C # object clone

Source: Internet
Author: User
ArticleDirectory
    • Shallow vs. Deep cloning
    • Icloneable Interface
    • Type-safe clone
    • 1. Clone manually
    • 2. Clone with memberwiseclone
    • 3. Clone with reflection
    • 4. Clone with serialization
    • 5. Clone with IL
    • 6. Clone with extension methods
C # object Clone Wars

Cloning C # objects is one of those things that appears easy but is actually quite complicated with equal "gotchas." This article describes the most common ways to clone a C # object.

 

Shallow vs. Deep cloning

There are two types of object cloning: shallow and deep.A shallow clone copies the references but not the referenced objects. A deep clone copies the referenced objects as well.

Hence, a reference in the original object and the same reference in a shallow-cloned object both point to the same object. whereas a deep-cloned object contains a copy of everything directly or indirectly referenced by the object. see Wikipedia for a detailed explanation.

Icloneable Interface

The icloneable Interface contains a single clone method, which is used to create a copy of the current object.

Public Interface Icloneable
{
Object Clone();
}

The problem with icloneable is that the clone method does not explicitly specify whether it is creating a shallow or deep copy, so callers can never be sure. hence, there is some discussion about making icloneable obsolete in. net Framework. the msdn documentation seems to hint that clone shocould perform a deep copy, but it is never explicitly stated:

The icloneable Interface contains one member, clone, which is intended to support cloning beyond that supplied by memberwiseclone...The memberwiseclone method creates a shallow copy...

Type-safe clone

Another disadvantage of icloneable is that the clone method returns an object, hence every clone call requires a cast:

Person Joe=New Person();
Joe.Name="Joe Smith";
Person Joeclone= (Person)Joe.Clone();

One way to avoid the cast is to provide your own type-safe clone method. Note that you must still provide the icloneable. Clone method to satisfy the icloneable interface:

  Public   class   person :  icloneable 
{
Public string name ;
Object icloneable . clone ()
{< br> return This . clone ();
}< br> Public person clone ()
{< br> return ( person ) This . memberwiseclone ();
}< BR >}
Clone options

Following are some of the more common approaches to clone a C # object:

1. Clone manually

One way to guarantee that an object will be cloned exactly how you want it is to manually clone every field in the object. the disadvantage to this method is it's tedious and error prone: If you add or change a field in the class, chances are you will forget to update the clone method. note that care must be taken to avoid an infinite loop when cloning referenced objects that may refer back to the original object. here is a simple example that performs a deep copy:

 Public   Class   Person : Icloneable
{
Public String Name ;
Public Person Spouse ;
Public Object Clone ()
{
Person P = New Person ();
P . Name = This . Name ;
If ( This . Spouse ! = Null )
P . Spouse = ( Person ) This . Spouse . Clone ();
Return P ;
}
}
2. Clone with memberwiseclone

Memberwiseclone is a protected method in the object class that creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object. for value-type fields, this performs a bit-by-bit copy. for reference-type fields, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object. note This works for all derived classes, and hence you only need to define the clone method once in the base class. here is a simple example:

Public Class Person:Icloneable
{
Public String Name;
Public Person Spouse;
Public Object Clone()
{
Return This.Memberwiseclone();
}
}
3. Clone with reflection

Cloning by reflection uses activator. createinstance to create a new object of the same type, then performs a shallow copy of each field using reflection. the advantage of this method is it's automatic and does not need to be adjusted when members are added or removed from the object. also, it can be written to provide a deep copy. the disadvantage is it uses reflection, which is slower and not allowed in partial trust environments. sample Code

4. Clone with serialization

One of the easiest ways to clone an object is to serialize it and immediately deserialize it into a new object. like the reflection approach, the serialization approach is automatic and does not need to be adjusted when members are added or removed from the object. the disadvantage is that serialization can be slower than other methods including reflection, and all cloned and referenced objects must be marked serializable. also, depending on what type of serialization you use (XML, SOAP, binary), private members may not be cloned as desired. sample Code here and here.

5. Clone with IL

A fringe solution is to use il (intermediate language) to clone objects. this approach creates a dynamicmethod, gets the ilgenerator, emits code in the method, compiles it to a delegate, and executes the delegate. the delegate is cached so that the Il is generated only the first time and not for each subsequent cloning. although this approach is faster than reflection, it is difficult to understand and maintain. sample Code

6. Clone with extension methods

Havard stranden created a custom cloning framework using extension methods. the framework creates a deep copy of an object and all referenced objects, no matter how complex the object graph is. the disadvantage is this is a custom framework with no source code (Update: source code now encoded, see comment below), and it cannot copy objects created from private classes without parameterless constructors. another problem, which is common to all automated deep copy methods, is that deep copying often requires intelligence to handle special cases (such as unmanaged resources) that cannot be easily automated.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.