Clone an Object

image_pdfimage_print
   
 

///////////////////////////////////////////////////////////////////////////////////////////////
//
//    This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
//    Copyright (c) 2005-2008, Jim Heising
//    All rights reserved.
//
//    Redistribution and use in source and binary forms, with or without modification,
//    are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright notice,
//      this list of conditions and the following disclaimer in the documentation and/or
//      other materials provided with the distribution.
//
//    * Neither the name of Jim Heising nor the names of its contributors may be
//      used to endorse or promote products derived from this software without specific prior
//      written permission.
//
//    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//    IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
//    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
//    NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//    WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
//    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//    POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Text;

namespace WOSI.Utilities
{
    public class ObjectUtils
    {
        public static object Clone(object objectToClone)
        {
            object dataObject = Activator.CreateInstance(objectToClone.GetType());

            // Fill in our class fields
            foreach (System.Reflection.FieldInfo field in dataObject.GetType().GetFields())
            {
                try
                {
                    if (field.IsPublic)
                    {
                        field.SetValue(dataObject, objectToClone.GetType().GetField(field.Name).GetValue(objectToClone));
                    }
                }
                catch
                {
                }
            }

            // Fill in our class properties
            foreach (System.Reflection.PropertyInfo property in dataObject.GetType().GetProperties())
            {
                try
                {
                    if (property.PropertyType.IsPublic && property.CanWrite)
                    {
                        property.SetValue(dataObject, objectToClone.GetType().GetProperty(property.Name).GetValue(objectToClone, null), null);
                    }
                }
                catch
                {
                }
            }

            return dataObject;
        }
    }
}

   
     


Implements ICloneable

image_pdfimage_print
   
  

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}
", 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);
    }
}

   
     


System.Array and the Collection Classes:ICloneable 2

image_pdfimage_print

   
 

using System;
class ContainedValue
{
    public ContainedValue(int count)
    {
        this.count = count;
    }
    public int count;
}
class MyObject
{
    public MyObject(int count)
    {
        this.contained = new ContainedValue(count);
    }
    public MyObject Clone()
    {
        return((MyObject) MemberwiseClone());
    }
    public ContainedValue contained;
}
public class SystemArrayandtheCollectionClassesICloneable2
{
    public static void Main()
    {
        MyObject    my = new MyObject(33);
        MyObject    myClone = 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);
    }
}
           
         
     


System.Array and the Collection Classes:ICloneable 1

image_pdfimage_print

   
 

using System;
class ContainedValue
{
    public ContainedValue(int count)
    {
        this.count = count;
    }
    public int count;
}
class MyObject: ICloneable
{
    public MyObject(int count)
    {
        this.contained = new ContainedValue(count);
    }
    public object Clone()
    {
        Console.WriteLine("Clone");
        return(new MyObject(this.contained.count));
    }
    public ContainedValue contained;
}
public class SystemArrayandtheCollectionClassesICloneable
{
    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);
    }
}

           
         
     


Demonstrate ICloneable

image_pdfimage_print

   
 
/*
C#: The Complete Reference 
by Herbert Schildt 

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

// Demonstrate ICloneable. 
 
using System;  
 
class X { 
  public int a; 
 
  public X(int x) { a = x; } 
} 
 
class Test : ICloneable { 
  public X o; 
  public int b; 
 
  public Test(int x, int y) { 
    o = new X(x); 
    b = y; 
  } 
 
  public void show(string name) { 
    Console.Write(name + " values are "); 
    Console.WriteLine("o.a: {0}, b: {1}", o.a, b); 
  } 
 
  // Make a deep copy of the invoking object. 
  public object Clone() { 
    Test temp = new Test(o.a, b); 
    return temp; 
  } 
     
} 
  
public class CloneDemo {     
  public static void Main() {     
    Test ob1 = new Test(10, 20); 
 
    ob1.show("ob1"); 
 
    Console.WriteLine("Make ob2 a clone of ob1."); 
    Test ob2 = (Test) ob1.Clone(); 
 
    ob2.show("ob2"); 
 
    Console.WriteLine("Changing ob1.o.a to 99 and ob1.b to 88."); 
    ob1.o.a = 99; 
    ob1.b = 88; 
 
    ob1.show("ob1"); 
    ob2.show("ob2"); 
  } 
}


           
         
     


Copy a class

image_pdfimage_print

   
 
/*
C#: The Complete Reference 
by Herbert Schildt 

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Copy a class. 
 
using System; 
 
// Define a structure. 
class MyClass { 
  public int x; 
} 
 
// Now show a class object assignment. 
public class ClassAssignment { 
  public static void Main() { 
    MyClass a = new MyClass(); 
    MyClass b = new MyClass(); 
 
    a.x = 10; 
    b.x = 20; 
 
    Console.WriteLine("a.x {0}, b.x {1}", a.x, b.x); 
 
    a = b; 
    b.x = 30; 
 
    Console.WriteLine("a.x {0}, b.x {1}", a.x, b.x); 
  } 
}


           
         
     


declare a class Address containing the data members to describe a US address along with the member functions

image_pdfimage_print
   
 


using System;

class MainClass {
    public static void Main(string[] args) {
        Address addr = new Address();
        addr.SetStreet(123, "My Street");
        addr.SetCity("A", "X", 123456);

        Console.WriteLine(addr.GetStreetString());
        Console.WriteLine(addr.GetCityString());

        addr.Output();

    }
}

class Address {
    public int nAddressNumberPart;
    public string sAddressNamePart;

    public string sCity;
    public string sState;
    public int nPostalCode;

    public void SetStreet(int nNumber, string sName) {
        nAddressNumberPart = nNumber;
        sAddressNamePart = sName;
    }

    public string GetStreetString() {
        return nAddressNumberPart + " " + sAddressNamePart;

    }
    public void SetCity(string sCityIn, string sStateIn, int nPostalCodeIn) {
        sCity = sCityIn;
        sState = sStateIn;
        nPostalCode = nPostalCodeIn;
    }
    public string GetCityString() {
        return sCity + ", " + sState + " " + nPostalCode;
    }
    public string GetAddressString() {
        return GetStreetString() + "
" + GetCityString();
    }

    public void Output() {
        Console.WriteLine(GetAddressString());
    }
}