Object copy or clone

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am implementing object copying in C#. I can think of two ways: (1)Use the famous C++ way of copy constructor, (2)Use IClonable interface.
I have inherited classes that I would like to implement copying. Which is the best way in C#
Thanks for the help in advance

Michael
 
The only reason the ICloneable interface would be preferable would be if you
need to give your objects to some System.* class that uses that interface to
clone your objects. Some collections may do this. Since constructors aren't
a part of interfaces, you can't have an interface that says the class has a
copy constructor.

What I'm saying is that I think the difference between the two methods is
exactly the same as the difference between using interfaces or not using
interfaces in general.

Chris

Michael said:
I am implementing object copying in C#. I can think of two ways: (1)Use
the famous C++ way of copy constructor, (2)Use IClonable interface.
 
Michael,
The .NET method is to implement the IClonable interface, as you can enable
it to behave polymorphically. IClonable is relatively easy to implement with
Object.MemberwiseClone, if your hierarchary supports shallow copies.

There was a long thread in microsoft.public.dotnet.general from about 3 Jan
04 titled "Copy constructors and clones" that discusses why IClonable is
"better" then copy constructors.

It also discusses why one may want to implement IClonable in terms of a
protected copy constructor (to support deep copy of Readonly fields).

You should be able to search http://groups.google.com for the thread.

In addition to copy constructors & cloning, you could also use serialization
to make a copy of an object. (Implementiong IClonable in terms of
serialization is an option, especially when you already implement
serialization).

Hope this helps
Jay

Michael said:
I am implementing object copying in C#. I can think of two ways: (1)Use
the famous C++ way of copy constructor, (2)Use IClonable interface.
 
Back
Top