Implements ICloneable : Clone « Class Interface « C# / C Sharp






Implements ICloneable

  

using System;
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 Team : ICloneable {
    public List<Employee> TeamMembers = new List<Employee>();

    public Team() {
    }

    private Team(List<Employee> members) {
        foreach (Employee e in members) {
            TeamMembers.Add((Employee)e.Clone());
        }
    }

    public void AddMember(Employee member) {
        TeamMembers.Add(member);
    }

    public override string ToString() {
        StringBuilder str = new StringBuilder();
        foreach (Employee e in TeamMembers) {
            str.AppendFormat("  {0}\r\n", e);
        }

        return str.ToString();
    }

    public object Clone() {
        return new Team(this.TeamMembers);
    }
}

public class MainClass {
    public static void Main() {
        Team team = new Team();
        team.AddMember(new Employee("F", "Developer", 34));
        team.AddMember(new Employee("K", "Tester", 78));
        team.AddMember(new Employee("C", "Support", 18));

        Team clone = (Team)team.Clone();

        Console.WriteLine(team);
        Console.WriteLine(clone);

        Console.WriteLine(Environment.NewLine);
        team.TeamMembers[0].Name = "NewName";
        team.TeamMembers[0].Title = "Manager";
        team.TeamMembers[0].Age = 44;

        Console.WriteLine(team);
        Console.WriteLine(clone);
    }
}

   
  








Related examples in the same category

1.Copy a classCopy a class
2.Demonstrate ICloneableDemonstrate ICloneable
3.System.Array and the Collection Classes:ICloneable 1System.Array and the Collection Classes:ICloneable 1
4.System.Array and the Collection Classes:ICloneable 2System.Array and the Collection Classes:ICloneable 2
5.Clone an Object