Sunday, September 7, 2008

Perform shallow copy of an object : example

To Perform shallow copy of an object MemberwiseClone() function is used.
In this example, you can also observe the behavior of static and non-static members.
To understand this function create Console Application.
In Console Application create class MyBaseClass as follows.
  class MyBaseClass
  {
  public static string CompanyName = "My Company";
  public int age;
  public string name;
   
//overides to string method
  public override string ToString()
  {
  return string.Format("CompanyName = {0}, age = {1}, name = {2}", CompanyName, age, name);
  }
  }
Now, Rename Program.cs to MyDerivedClass.cs,  paste following code,  and check output.
  class MyDerivedClass : MyBaseClass
  {
  static void Main(string[] args)
  {
  // Creates an instance of MyDerivedClass and assign values to its fields.
  MyDerivedClass m1 = new MyDerivedClass();
  MyDerivedClass.CompanyName = "Softweb Solutions";
  m1.age = 42;
  m1.name = "Sam";

  //Performs a shallow copy of m1 and assign it to m2. (Value Type)
  MyDerivedClass m2 = (MyDerivedClass)m1.MemberwiseClone();

  //Performs a copy of m1 and assign it to m3. (Reference Type)
  MyDerivedClass m3 = m1;


  Console.WriteLine("\nBefore Change");

  Console.WriteLine("Object m1---------:" + m1.ToString());
  Console.ReadKey();

  Console.WriteLine("Object m2---------:" + m2.ToString());
  Console.ReadKey();

  Console.WriteLine("Object m3---------:" + m3.ToString());
  Console.ReadKey();

  //Now Change m1 and print m1, m2, and m3
  MyDerivedClass.CompanyName = "TRC";
  m1.age = 100;
  m1.name = "Charles";

  Console.WriteLine("\n\nAfter Change");

  Console.WriteLine("Object m1---------:" + m1.ToString());
  Console.ReadKey();

  Console.WriteLine("Object m2---------:" + m2.ToString());
  Console.ReadKey();

  Console.WriteLine("Object m3---------:" + m3.ToString());
  Console.ReadKey(); 
  }
  }

No comments: