How do I implement ICloneable?

  • Thread starter Thread starter Don
  • Start date Start date
D

Don

Can anyone give me an example of implementing ICloneable to give a class I
created a "Clone" method so I can make copies of objects. I have no idea
where to begin with this. Thanks.

- Don
 
Don

Does your object have references to other objects in it? If so, do you want
to Clone them as well or do you just want a shallow copy of the object?

If you want a shallow copy then this is all you need.

Public Function Clone As ObjectType Implements ICloneable.Clone
Return DirectCast (MemberwiseClone, ObjectType)
End Function

The Implements ICloneable.Clone tells it that the Icloenable is being
honoured. Without that it's just a function called Clone

If you want a deep copy, you have to call Clone for each sub-object and
assign the result back to the appropriate member.

Class Car
Private theSteeringWheel As SteeringWheel

Public Function Clone As ObjectType Implements ICloneable.Clone
Dim newCar As Car = DirectCast (MemberwiseClone, Car)
newCar.theSteeringWheel = newCar.theSteeringWheel.Clone
Return newCar
End Function

Richie
 
Back
Top