how to create an object duplicate  
Author Message
R.Tutus





PostPosted: Visual C# General, how to create an object duplicate Top

Hi

I show a form with: myForm.show(), then in myForm I create _customer object of type CustomerEntity . I want _customer object to be a copy of account.customer object, which means, I want to be able to modify _customer without modifying account.customer . Is there an easy way to do that, knowing that customer class is a business entity class that Implemented myself.

Thank you for helping me learn.




Visual C#12  
 
 
Peter Ritchie





PostPosted: Visual C# General, how to create an object duplicate Top

The ICloneable interface is intended to provide a consistent interface that a class and implement the ability to perform a deep copy of an object. Otherwise, you can Object.MemberwiseClone can be used to create a shallow copy of an object.

 
 
R.Tutus





PostPosted: Visual C# General, how to create an object duplicate Top

Thanks for the icloneable idea.

In the second case, can I use MemberwiseClone directly create a copy of my first object account.customer or will I have to go through a derived class. I don t see why I should create a derived class, I have no need for that. Is that mandatory if I want to use MemberwiseClone

Thanks.



 
 
Peter Ritchie





PostPosted: Visual C# General, how to create an object duplicate Top

MemberwiseClone is a protected member of Object, so it can only be used within your class (you don't need to create another derived class, remember all classes derive from Object, so they'll have access to MemberwiseClose).

The recommended approach is to implement ICloneable:

class Cloneable : ICloneable

{

private int value;

public Cloneable ( int value )

{

this.value = value;

}

public int Value

{

get

{

return this.value;

}

}

#region ICloneable Members

public object Clone ( )

{

return MemberwiseClone();

}

#endregion

}


Cloneable mc = new Cloneable(42);

Cloneable mcClone = mc.Clone() as Cloneable;

System.Diagnostics.Debug.Assert(mcClone.Value == mc.Value && mcClone != mc);


In this example the Clone method simply defers to MemberwiseClone, but it's quicker to implement your own algorithm as MemberwiseClone would use Reflection...

 
 
R.Tutus





PostPosted: Visual C# General, how to create an object duplicate Top

sorry peter. I see 2 methods: Cloneable and clone. In your example, did u implement both ways of doing things: one using MemberwiseClone and one without using MemberwiseClone or should I use your code all together.

Thanks for explaining.