ICloneable interface
In this chapter you will learn:
Implement ICloneable interface
The following code implements the ICloneable interface.
using System;//from j a v a 2s. co m
class MyValue
{
public MyValue(int count)
{
this.count = count;
}
public int count;
}
class MyObject: ICloneable
{
public MyObject(int count)
{
this.contained = new MyValue(count);
}
public object Clone()
{
Console.WriteLine("Clone");
return(new MyObject(this.contained.count));
}
public MyValue contained;
}
class MainClass
{
public static void Main()
{
MyObject my = new MyObject(33);
MyObject myClone = (MyObject) my.Clone();
Console.WriteLine("Values: {0} {1}", my.contained.count, myClone.contained.count);
myClone.contained.count = 15;
Console.WriteLine("Values: {0} {1}", my.contained.count, myClone.contained.count);
}
}
The code above generates the following result.
Clone a list of objects
The following clone implementation for EmployeeList is not a deep copy. Deep copy means every single object in the list must also be a new instance.
using System;/*j a v a 2 s . c o m*/
using System.Text;
using System.Collections.Generic;
public class Employee : ICloneable
{
public string Name;
public string Title;
public int Age;
public Employee(string name, string title, int age)
{
Name = name;
Title = title;
Age = age;
}
public object Clone()
{
return MemberwiseClone();
}
public override string ToString()
{
return string.Format("{0} ({1}) - Age {2}", Name, Title, Age);
}
}
public class EmployeeList : ICloneable
{
public List<Employee> EmployeeListMembers = new List<Employee>();
public EmployeeList()
{
}
private EmployeeList(List<Employee> members)
{
foreach (Employee e in members)
{
EmployeeListMembers.Add((Employee)e.Clone());
}
}
public void AddMember(Employee member)
{
EmployeeListMembers.Add(member);
}
public override string ToString()
{
StringBuilder str = new StringBuilder();
foreach (Employee e in EmployeeListMembers)
{
str.AppendFormat(" {0}\r\n", e);
}
return str.ToString();
}
public object Clone()
{
return new EmployeeList(this.EmployeeListMembers);
}
}
public class MainClass
{
public static void Main()
{
EmployeeList team = new EmployeeList();
team.AddMember(new Employee("A", "AA", 4));
team.AddMember(new Employee("B", "BB", 8));
team.AddMember(new Employee("C", "CC", 8));
EmployeeList clone = (EmployeeList)team.Clone();
Console.WriteLine("Original EmployeeList:");
Console.WriteLine(team);
Console.WriteLine("Clone EmployeeList:");
Console.WriteLine(clone);
Console.WriteLine("*** Make a change to original team ***");
team.EmployeeListMembers[0].Name = "L";
team.EmployeeListMembers[0].Title = "M";
team.EmployeeListMembers[0].Age = 4;
Console.WriteLine("Original EmployeeList:");
Console.WriteLine(team);
Console.WriteLine("Clone EmployeeList:");
Console.WriteLine(clone);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter: