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.Design Patterns
8.Development Class
9.Event
10.File Stream
11.Generics
12.GUI Windows Form
13.Language Basics
14.LINQ
15.Network
16.Office
17.Reflection
18.Regular Expressions
19.Security
20.Services Event
21.Thread
22.Web Services
23.Windows
24.Windows Presentation Foundation
25.XML
26.XML LINQ
C# / C Sharp by API
C# / CSharp Tutorial
C# / CSharp Open Source
C# / C Sharp » Class Interface » CloneScreenshots 
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
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.