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

Home
C# / C Sharp
1.2D Graphics
2.Class Interface
3.Collections Data Structure
4.Components
5.Data Types
6.Database ADO.net
7.Date Time
8.Design Patterns
9.Development Class
10.Event
11.File Stream
12.Generics
13.GUI Windows Form
14.Internationalization I18N
15.Language Basics
16.LINQ
17.Network
18.Office
19.Reflection
20.Regular Expressions
21.Security
22.Services Event
23.Thread
24.Web Services
25.Windows
26.Windows Presentation Foundation
27.XML
28.XML LINQ
C# / C Sharp » Class Interface » Clone 




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
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.