473,406 Members | 2,713 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

How do I implement ICloneable?

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
Nov 20 '05 #1
7 26405
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
Nov 20 '05 #2
Hello Don,

here's a small example of how you can implement ICloneable:

Public Class A
Implements ICloneable

Private myInt As Integer

Public Function Clone() As Object Implements System.ICloneable.Clone
Dim newInstance As New A

newInstance.myInt = myInt

Return newInstance
End Function
End Class

Note that there are two ways to implement ICloneable. You can either do a
deep copy or a shallow copy. A deep copy means that the object which
implements ICloneable will be copied and all object it points to will also
be copied. This is different from a shallow copy where the references to
objects are copied but the objects themselves are not. To make it more
clear, take the following class:

Class X
Private myMember As Y

Public Function Clone() As Object Implements System.ICloneable.Clone
Dim newInstance As New X
newInstance.myMember = myMember
Return newInstance
End Function
End Class

Where Y is another class. In this case, Clone is performing a shallow copy
because it's only assigning the reference myMember to the new instance. In
the end, both instances of X will point to the same instance of Y. In order
to perform a deep copy, Clone would have to create a copy of Y by calling
Clone on it for example. Note that in the first example I gave, you do not
have this problem because Integers are value types as opposed to reference
types.

As you can see, the semantic of ICloneable is not clear. It depends on how
it was implemented. For that reason, it is suggested that you use a
different mechanism if you are going to expose your classes publicly. For
example, you could provide a Copy method and clearly document its behavior.
That way you can avoid confusion for the clients of your class.

HTH

Antoine
Microsoft Visual Basic .NET

This posting is provided "AS IS" with no warranties, and confers no rights.

--------------------
X-Trace-PostClient-IP: 24.79.64.248
From: "Don" <un*****@oblivion.com>
Newsgroups: microsoft.public.dotnet.languages.vb
Subject: How do I implement ICloneable?
Lines: 7
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 6.00.2800.1106
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1106
Message-ID: <10Qpb.289462$6C4.181276@pd7tw1no>
Date: Tue, 04 Nov 2003 15:57:49 GMT
NNTP-Posting-Host: 24.66.94.143
X-Complaints-To: ab***@shaw.ca
X-Trace: pd7tw1no 1067961469 24.66.94.143 (Tue, 04 Nov 2003 08:57:49 MST)
NNTP-Posting-Date: Tue, 04 Nov 2003 08:57:49 MST
Organization: Shaw Residential Internet
Path: cpmsftngxa06.phx.gbl!TK2MSFTNGP08.phx.gbl!newsfeed 00.sul.t-online.de!t-onlin
e.de!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!newshub .sdsu.edu!elnk-n
f2-pas!elnk-pas-nf1!newsfeed.earthlink.net!pd7cy1no!shaw.ca!pd7tw1 no.POSTED!
53ab2750!not-for-mailXref: cpmsftngxa06.phx.gbl microsoft.public.dotnet.languages.vb:153496
X-Tomcat-NG: microsoft.public.dotnet.languages.vb

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

This posting is provided "AS IS" with no warranties, and confers no rights.

Nov 20 '05 #3
Hi Richie,

Unfortunately ICloneable.Clone must return an Object - it can't be a
specific type such as the ObjectType that you show.

The DirectCast is then no longer applicable and would have to be done by
the caller.That would mean it becomes simply:

Public Function Clone As Object Implements ICloneable.Clone
Return MemberwiseClone
End Function

With your Car example it would be used like so:
Dim oNewCar As Car _
= DirectCast (oOriginalCar.Clone, Car)

In order to avoid this necessity, it is entirely feasible to forget the
ICloneable Interface and simply implement Clone as you originally defined it -
(almost)

Public Function Clone As Car
Return DirectCast (MemberwiseClone, Car)
or
'The deep clone stuff
End Function

ICloneable is not necessary for offering Clone except in certain
situations where you need polymorphic access to Clone.

Note that an Object may offer a deep Clone by cloning all referred object,
but these themselves will offer shallow <or> deep depending on how they were
designed.

Regards,
Fergus
Nov 20 '05 #4
Richie,
In addition to Fergus's comments I normally offer both Clone methods.

Public Function Clone As Car
Return DirectCast (MemberwiseClone, Car)
or
'The deep clone stuff
End Function

Private Function ICloneable_Clone As Object Implements ICloneable.Clone
Return Clone()
End Function

Notice that the version that Implements ICloneable.Clone is marked as
Private and has ICloneable as part of the name, this effectively hides the
function, while allowing it to be used for the ICloneable interface. I
simply call the Clone As Car method, as the implementation is the same.

In fact in my current project I have these methods in my base class, The
Clone As Car method is MustOverride as I polymophically call the Clone
method. As Fergus stated, ICloneable is not specifically required, however
its good to have on the class to identify that the class supports cloning...

Hope this helps
Jay

"Richie Glenn" <hi**@gmx.at> wrote in message
news:Oj**************@TK2MSFTNGP10.phx.gbl...
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

Nov 20 '05 #5
Hi Jay,

How come the Private member is available through the Interface? Does being
an Interface implementation method override this privacy. No, another view -
does it have a dual identity - Private in its Car guise yet Public as an
ICloneable method? Is this the OOP version of superheroes like Batman/Bruce
Wayne? (forget that last question, lol)

Regards,
Fergus
Nov 20 '05 #6
Fergus,
It has dual identity: To the Car class itself the method is Private. However
because it has the Implements ICloneable.Clone on the declaration is it
Public to the ICloneable interface.

Which means if I have an ICloneable variable with a Car object in it. I can
use the Clone method and the Car.ICloneable_Clone method will be called
transparently by the Framework. However If I have a Car variable with a Car
object in it, only methods inside Car can call it.

Which I find is part of the beauty of the how VB.NET Implements works. If
you use C# it has a similar ability using "ICloneable.Clone" for the method
name which actually hides it from the Car class itself, you can only access
the method via the interface. In VB.NET I can do:

Public Function CreateCopy() As Object Implements ICloneable.Clone

I renamed the ICloneable.Clone method in the public interface of Car. C#
needs two functions to do the above! One for the CreateCopy method, and one
to hide ICloneable.Clone.

Which is also why if you look at the "Windows Form Designer generated code"
section of a form you will occasionally see:

CType(Me.grid, System.ComponentModel.ISupportInitialize).BeginIni t()

The Forms designer knows that the object in the grid variable implements the
ISupportInitialize interface, but the BeginInit method may be hidden or
renamed using the above technique.

NOTE: Some OOP developers/designer feel it is wrong to hide the
implementation of an interface. That when you say a class Implements an
Interface that all methods of that Interface need to be public "as per the
interface definition", which follows the inheritance rule, this Class IS A
this Interface. I tend to relax a little on this point, as Implementing the
Interface may be an Implementation detail (such as ISerializable). The
ISerializable.GetObjectData may be an implementation detail in which case it
should not be public. The fact my object is Serializable & supports the
ISerializable interface is an implementation detail. Either way you feel, it
is advantageous that .NET (VB.NET & C#) supports the ability.

Hope this helps
Jay

"Fergus Cooney" <fi****@post.com> wrote in message
news:ec**************@TK2MSFTNGP10.phx.gbl...
Hi Jay,

How come the Private member is available through the Interface? Does being an Interface implementation method override this privacy. No, another view - does it have a dual identity - Private in its Car guise yet Public as an
ICloneable method? Is this the OOP version of superheroes like Batman/Bruce Wayne? (forget that last question, lol)

Regards,
Fergus

Nov 20 '05 #7
Hi Jay,

Thanks for that. I go with the hide-the-details when I choose. Having a
strongly typed Clone but an ICloneable with a different name still available
using 'Clone' makes good sense to me.

Regards,
Fergus
Nov 20 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: smith | last post by:
I've been making deep copy clones of objects since my second week or so with ..Net (it took me the first week to realize that shallow copies were usually worthless as "clones"). Normally I call my...
1
by: Michael D. Ober | last post by:
In VB 2005, the ICloneable interface requires the following: Class foo Implements ICloneable Public Function Clone() as Object Implements System.ICloneable.Clone ' return new_object of type...
1
by: Hasani | last post by:
I have an object called FileNode and it implements ICloneable which creates a deep copy of the FileNode. The one of the constructors for ArrayList use an ICollection as a paremeter. If I pass that...
4
by: Peter | last post by:
I want to copy a parent class instance's all datas to a child's. It's actually a C++'s copy constructor. But why the following code does not work - there is a compile error! How it should look...
6
by: Andy | last post by:
Hello. I've got an issue with the ICloneable interface that makes me think I'm missing the advantages of it. My issue is that the implemented Clone method returns an object and not a strongly...
2
by: Venkat Venkataramanan | last post by:
Hello: I have an object Users that implements the ICloneable interface. I am trying to pass an instance of this object, foUser from one form into a second form ByRef. Dim formLogin As New...
2
by: Nathan | last post by:
I'm working with Clone() for the first time, and noticed that you have to unbox the Clone of an object that implements ICloneable: MyObject var1 = new MyObject(); // Where MyObject implements...
3
by: ib | last post by:
ICloneable::Clone returns a new instance of the object being cloned. However, it seems possible that the garbage collector could release this memory before the calling function receives a reference...
6
by: Stefan Hoffmann | last post by:
hi, the following implementations work: public class NullSafeCollection: System.Collections.CollectionBase, System.ICloneable { object System.IClonable.Clone() { NullSafeCollection clone =...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.