Object assignment

   
 


using System;
public class Foo
{
    public int i;
}
   
class RefTest1App
{
    static void Main(string[] args)
    {
        Foo test1 = new Foo();
        test1.i = 1;
   
        Foo test2 = new Foo();
        test2.i = 2;
   
        Console.WriteLine("BEFORE OBJECT ASSIGNMENT");
        Console.WriteLine("test1.i={0}", test1.i);
        Console.WriteLine("test2.i={0}", test2.i);
        Console.WriteLine();
   
        test1 = test2;
   
        Console.WriteLine("AFTER OBJECT ASSIGNMENT");
        Console.WriteLine("test1.i={0}", test1.i);
        Console.WriteLine("test2.i={0}", test2.i);
        Console.WriteLine();
   
        test1.i = 42;
   
        Console.WriteLine("AFTER CHANGE TO ONLY TEST1 MEMBER");
        Console.WriteLine("test1.i={0}", test1.i);
        Console.WriteLine("test2.i={0}", test2.i);
    }
}

    


Object.ReferenceEquals Method

   
 

using System;


public class Starter {
    public static void Main() {
        Employee obj1 = new Employee(5678);
        Employee obj2 = (Employee)obj1.Clone();
        if (Employee.ReferenceEquals(obj1, obj2)) {
            Console.WriteLine("objects identical");
        } else {
            Console.WriteLine("objects not identical");
        }
    }
}
class Employee : ICloneable {
    public Employee(int id) {
        if ((id < 1000) || (id > 9999)) {
            throw new Exception(
                "Invalid Employee ID");
        }

    }
    public object Clone() {
        return MemberwiseClone();
    }
}

    


Object Copy and Clone


   

using System;
   
   
public class Name {
  public string firstName;
  public string lastName;
   
  public Name(string firstName, string lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
   
  public void Display() {
    Console.WriteLine("firstName = " + firstName);
    Console.WriteLine("lastName = " + lastName);
  }
   
  public static Name Copy(Name car) {
    return (Name) car.MemberwiseClone();
  }
}
   
   
class Test {
  public static void Main() {
    Name myName = new Name("T", "M");
    Name myOtherName = new Name("P", "B");
    Console.WriteLine("myName details:");
    myName.Display();
    Console.WriteLine("myOtherName details:");
    myOtherName.Display();
   
    // perform a memberwise clone of myName using the Name.Copy() method
    Console.WriteLine("Performing a memberwise clone of myName to myOldName");
    Name myOldName = Name.Copy(myName);
    Console.WriteLine("myOldName details:");
    myOldName.Display();
  }
   
}