Looking for a uniform way for deep-copy

M

marcosegurini

Hi,

the following class describes my actual problem:

class DeepCopy<T>
{
T val_;

public void Assign(T newVal)
{
// Here I like to perform DEEP-COPY of newVal and assign it to
val_.
}
}

I am looking for a uniform way to perform the deep-copy for both
reference and value types.

This uniform way should not use the ICloneable interface because my
program uses System.Drawing.Point at-large (and other existing
class/struct) that does not implement this interface.

Thanks a lot for any suggestion.
Marco.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

I don;t think that it can be done, it's dependand of the type you want to
deep-copy , it's the creator of the class then one who knows how to clone
it.
The class may has private components that are important to create a clone
and that you have no access to them.

Maybe using reflection you could do something, but I don;t know if it will
work always.


Cheers,
 
A

Alan Pretre

Hi,

the following class describes my actual problem:

class DeepCopy<T>
{
T val_;

public void Assign(T newVal)
{
// Here I like to perform DEEP-COPY of newVal and assign it to
val_.
}
}

I am looking for a uniform way to perform the deep-copy for both
reference and value types.

This uniform way should not use the ICloneable interface because my
program uses System.Drawing.Point at-large (and other existing
class/struct) that does not implement this interface.

Thanks a lot for any suggestion.
Marco.

If I understand you correctly, you are looking for a way to deep copy a
generic <T> without wanting to hardcode all of the members in the copy
routine. You can serialize the object to a memory stream then deserialize
it back into the destination. Depending on the types of the objects being
deepcopied, they may need to manually implement ISerializable.

-- Alan
 
L

Lebesgue

By the way, you do not need to clone value types.
Point myPoint = new Point(100,150);
Point secondPoint = myPoint;
is completely OK, because actual values, not references are copied
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

No really, what if you have

struct A
{
int i;
object o;
}

A is a value type but you have a component of it that is a reference.


Cheers,
 
L

Lebesgue

No really, what if you have
struct A
{
int i;
object o;
}

A is a value type but you have a component of it that is a reference.

yes, you are right, I thought just of a System.Drawing.Point, sorry for
possible confusion
 

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

Top