Object.MemberwiseClone Method in C# with Examples
Last Updated :
23 Mar, 2022
Object.MemberwiseClone Method is used to create a shallow copy or make clone of the current Object. Shallow copy is a bit-wise copy of an object. In this case, a new object is created and that object has an exact copy of the existing object. Basically, this method copies the non-static fields of the current object to the new object.
- If a field is a reference type, then the only reference is copied not the referred object. So here, the cloned object and the original object will refer to the same object.
- If the field is value type then the bit-by-bit copy of the field will be performed.
Syntax:
protected object MemberwiseClone ();
Returns: This method returns a Object, which is the shallow copy of existing Object. Example 1:
csharp
using System;
class GFG1 {
public int val;
public GFG1( int val)
{
this .val = val;
}
}
class GFG2 {
public GFG1 gg;
public GFG2( int val)
{
this .gg = new GFG1(val);
}
public GFG2 Clone()
{
return ((GFG2)MemberwiseClone());
}
}
class Geek {
public static void Main()
{
GFG2 g = new GFG2(3);
GFG2 cc = g.Clone();
Console.WriteLine("Value: " + g.gg.val);
Console.WriteLine("cloned value: " + cc.gg.val);
cc.gg.val = 6;
Console.WriteLine("\nValue: " + g.gg.val);
Console.WriteLine("cloned value: " + cc.gg.val);
}
}
|
Output:
Value: 3
cloned value: 3
Value: 6
cloned value: 6
Example 2:
csharp
using System;
public class GFG : ICloneable {
public string Name;
public string Surname;
public int Age;
public GFG( string name,
string title, int age)
{
Name = name;
Surname = title;
Age = age;
}
public object Clone()
{
return MemberwiseClone();
}
public override string ToString()
{
return string .Format("Name = {0}, Surname = {1}, Age {2}",
Name, Surname, Age);
}
}
public class MainClass {
public static void Main()
{
GFG g = new GFG("ABC", "XYZ", 26);
GFG cg = (GFG)g.Clone();
Console.WriteLine("For Old values\nOriginal :");
Console.WriteLine(g);
Console.WriteLine("Cloned :");
Console.WriteLine(cg);
Console.WriteLine("\nAfter assigning new values");
g.Name = "LMN";
g.Surname = "QRS";
g.Age = 13;
Console.WriteLine("Original :");
Console.WriteLine(g);
Console.WriteLine("Cloned :");
Console.WriteLine(cg);
}
}
|
Output:
For Old values
Original :
Name = ABC, Surname = XYZ, Age 26
Cloned :
Name = ABC, Surname = XYZ, Age 26
After assigning new values
Original :
Name = LMN, Surname = QRS, Age 13
Cloned :
Name = ABC, Surname = XYZ, Age 26
Reference:
Share your thoughts in the comments
Please Login to comment...