views:

21

answers:

2

Hi All

I am using this.MemberwiseClone() to create shallowcopy but it is not working. Please look at the code below.

public class Customer
    {

        public int Id;
        public string Name;

        public Customer CreateShallowCopy()
        {
            return (Customer)this.MemberwiseClone();
        }
    }

class Program
{
    static void Main(string[] args)
    {
        Customer objCustomer = new Customer() { Id = 1, Name = "James"};
        Customer objCustomer2 = objCustomer;

        Customer objCustomerShallowCopy = objCustomer.CreateShallowCopy();

        objCustomer.Name = "Jim";
        objCustomer.Id = 2;            
    }
}

When I run the program, It shows objCustomerShallowCopy.Name as "James" rather than "Jim".

Any Ideas??

A: 

We have also had problems getting that to work. We have solved it by serializing and then deserializing the object.

public static T DeepCopy<T>(T item)
{
    BinaryFormatter formatter = new BinaryFormatter();
    MemoryStream stream = new MemoryStream();
    formatter.Serialize(stream, item);
    stream.Seek(0, SeekOrigin.Begin);
    T result = (T)formatter.Deserialize(stream);
    stream.Close();
    return result;
}

Using the above code there will be no reference between the two objects.

Shiraz Bhaiji
+2  A: 

When you shallow copy the Customer object the objCustomerShallowCopy.Name will be James and will stay like that until you change that object. Now in your case the string "James" will gave 3 references to it (objCustomer, objCustomer2 and objCustomerShallowCopy).

When you are changing objCustomer.Name to Jim you are actually creating a new string object for the objCustomer object and releasing 1 ref to the "James" string object.

Mark PM
How do I go about changing "objCustomer" properties (reference types) so that I can see the change reflected in "objCustomerShallowCopy" ??
Subhasis
In that case why use clone in the first place? Simply set objCustomerShallowCopy = objCustomer
Mark PM
My Question is why is not working....Is a bug in the Framework ???
Subhasis
Why does the documentation says MemberwiseClone does a shallow copy while in actual it is not doing do. It is doing a deep copy.
Subhasis
`MemberwiseClone` is making a shallow copy, as the documentation describes. You have to remember that strings are immutable. As the answer says, When you assign `objCustomer.Name = "Jim"`, you're creating a new string object and assigning it to `objCustomer.Name`. The "problem" is that you're not understanding the meaning of "shallow copy".
Jim Mischel
Nevermind...I figured it out..It is indeed doing a shallow copy.. Tested it by adding another member Address in Customer Class. Address having a int member. When I changed by objCustomer.Address.Pincode = 456, it was reflected in objCustomerShallowcopy.
Subhasis