Tuesday, March 11, 2014

Clone objects C#

Cloning is a matter between copy object and copy its references. There are two types of cloning, deep clone and shallow clone. If you copy only references it’ll call shallow copy. If you copy referenced objects it’ll call deep copy.
Shallow copy:

Vehicle vehicleOne = new Vehicle();
Vehicle vehicleTwo = new Vehicle();
vehicleOne = vehicleTwo;
view raw gistfile1.cs hosted with ❤ by GitHub
Deep copy:
There are two ways of doing this.
1. Use the copy constructor (a good practice)
class Vehicle
{
// Copy constructor.
public Vehicle (Vehicle previousVehicle)
{
Name = previousVehicle.Name;
Year = previousVehicle.Year;
}
//// Alternate copy constructor calls the instance constructor.
//public Vehicle (Vehicle previous Vehicle)
// : this(previousVehicle.Name, previousVehicle.Year)
//{
//}
// Instance constructor.
public Vehicle(string name, int year)
{
Name = name;
Year = year;
}
public int Year { get; set; }
public string Name { get; set; }
}
// Create a Vehicle object by using the instance constructor.
Vehicle vehicle1 = new Vehicle("Toyota", 2014);
// Create another Vehicle object, copying vehicle1.
Vehicle vehicle2 = new Vehicle(person1);
view raw gistfile1.cs hosted with ❤ by GitHub
2. Using ICloneable interface
Manual way
public class Vehicle: ICloneable
{
public string Name;
public int Year;
public object Clone()
{
Vehicle v = new Vehicle ();
v.Name = this.Name;
v.Year = this.Year;
return v;
}
}
view raw gistfile1.cs hosted with ❤ by GitHub
Using memberwiseclone
public class Vehicle : ICloneable
{
public string Name;
public int Year;
public object Clone()
{
return this.MemberwiseClone();
}
}
//how to use
Vehicle toyota = new Vehicle();
Vehicle toyotaClone = (Vehicle)toyota.Clone();
view raw gistfile1.cs hosted with ❤ by GitHub

No comments:

Post a Comment