PC Review


Reply
Thread Tools Rate Thread

Copy/Clone object

 
 
tshad
Guest
Posts: n/a
 
      26th Jan 2009
In C# how do I make an exact copy of an object.

I don't want to do:

ProjectObject a = new ProjectObject();
ProjectObject b;

b = a;

as I am pointing at the same object.

I thought I could do:

b = a.Clone();

But that doesn't work. I get an error;

Error 30 No overload for method 'Clone' takes '0'

How can I do this?

Thanks,

Tom


 
Reply With Quote
 
 
 
 
Göran Andersson
Guest
Posts: n/a
 
      26th Jan 2009
tshad wrote:
> In C# how do I make an exact copy of an object.
>
> I don't want to do:
>
> ProjectObject a = new ProjectObject();
> ProjectObject b;
>
> b = a;
>
> as I am pointing at the same object.
>
> I thought I could do:
>
> b = a.Clone();
>
> But that doesn't work. I get an error;
>
> Error 30 No overload for method 'Clone' takes '0'
>
> How can I do this?
>
> Thanks,
>
> Tom
>


There is no automatic cloning of objects, you have to implement this in
your class.

You can implement the IClonable interface, but as that is non-generic
the Clone method returns a reference to the type Object, so you have to
cast the referece. It's more convenient to have the Clone method return
a reference to the actual type of the object, but then it doesn't match
the IClonable interface.

So, there is no perfrect solution. There is an interface that exactly
matches what you want to do, but as it's pre-generics it's not so
convenient to use. You might want to make your own generic interface:

interface IClonable<T> {
T Clone();
}

public class ProjectObject : IClonable<ProjectObject> {

ProjectObject Clonse() {
// create a new ProjectObject instance and copy the data to it
}

}

Consider that there is shallow cloning and deep cloning. If your object
contains other object you can choose to copy their references or make
clones of them. If the objects are immutable, like for example the
String class, then you can safely copy the references.

--
Göran Andersson
_____
http://www.guffa.com
 
Reply With Quote
Reply

Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
How to clone an object ? =?Utf-8?B?QW5kcmV3?= Microsoft Dot NET Framework 2 6th Jun 2007 06:39 AM
How to clone an object? Rob R. Ainscough Microsoft VB .NET 2 17th Dec 2005 01:11 PM
Clone an object? Alfred Salton Microsoft ASP .NET 1 28th Jun 2004 06:53 PM
Object copy or clone =?Utf-8?B?TWljaGFlbA==?= Microsoft Dot NET Framework 2 3rd Feb 2004 03:36 AM
Re: clone a object Fergus Cooney Microsoft C# .NET 2 8th Sep 2003 10:20 PM


Features
 

Advertising
 

Newsgroups
 


All times are GMT +1. The time now is 05:21 AM.