This post will discuss how to copy objects in C#.

Copying an object is creating a copy of an existing object. This is usually done to modify or move the copy without impacting the original object.

1. Using Object.MemberwiseClone() method

The Object.MemberwiseClone() method can be used to create a shallow copy of the current Object. Refer to the Microsoft documentation to implement a deep copy with the MemberwiseClone() method.

The following example performs a shallow copy operation on X’s object using the MemberwiseClone() method.

Download  Run Code

2. Copy Constructor

The Copy Constructor takes another instance of the same class and defines the compiler’s actions when copying the object. The copy constructor implementation should perform deep copy for any referenced objects in the class by creating new objects and copying the immutable type’s values.

The following code example shows how to implement the copy constructor method. It also implements a static copy factory method that essentially does the same thing as the copy constructor method.

Download  Run Code

 
The problem with the copy constructors is their maintenance, i.e., if an object is structurally modified, you have to modify the copy constructor.

3. Deep Clone

The following code example demonstrates how to implement the deep cloning through BinaryFormatter Serialize() and Deserialize() methods. For this to work, mark your class as serializable through [Serializable].

Download  Run Code

That’s all about creating a copy of an object in C#.