Copy/Clone object

T

tshad

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
 
G

Göran Andersson

tshad said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top