how to clone a base class?

A

Amil Hanish

I have two classes that I have implemented ICloneable. From my top-level
class, how to I clone the base class values: See "how do I clone the base
class values" below. Since Clone returns an object, what do I assign it to
in my derived class?

public class Base : ICloneable
{
....
public object Clone()
{
....
}
}

public class Foo : Base, ICloneable
{
....
public object Clone()
{
.... // how do I clone the base class values
}
}
 
B

Bruce Wood

I solved this problem by implementing Clone() as a call to a protected
CopyTo() method:

public class Base : ICloneable
{
public object Clone()
{
return this.CopyTo(new Base());
}

protected virtual Base CopyTo(Base target)
{
.... copy Base fields here ...
}
}

public class Foo : Base
{
protected override Base CopyTo(Base target)
{
Foo newFoo = (Foo)base.CopyTo(new Foo());
.... copy Foo fields here ...
}
}
 
B

Bruce Wood

I solved this problem by implementing Clone() as a call to a protected
CopyTo() method:

public class Base : ICloneable
{
public object Clone()
{
return this.CopyTo(new Base());
}

protected virtual Base CopyTo(Base target)
{
.... copy Base fields here ...
}
}

public class Foo : Base
{
protected override Base CopyTo(Base target)
{
Foo newFoo = (Foo)base.CopyTo(new Foo());
.... copy Foo fields here ...
}
}
 
B

Bruce Wood

I solved this problem by implementing Clone() as a call to a protected
CopyTo() method:

public class Base : ICloneable
{
public object Clone()
{
return this.CopyTo(new Base());
}

protected virtual Base CopyTo(Base target)
{
.... copy Base fields here ...
}
}

public class Foo : Base
{
protected override Base CopyTo(Base target)
{
Foo newFoo = (Foo)base.CopyTo(new Foo());
.... copy Foo fields here ...
}
}
 
G

Guest

this is where ICloneable really doesn't quite work. what you should do is
have a protected copy constructor on both objects, and the copy constructor
of the derived class should call the copy constructor of the base class. and
ICloneable.Clone merely returns a new object by calling the copy constructor
and passing in itself.
 
G

Guest

Hi,
I wish to know why does base.clone does not work in .Net. In java if i do a
super.clone, it works fine. I have searched other newsgroups and was not
able find a reason for this behavior??
Prashant
 
J

Jon Skeet [C# MVP]

prashant said:
I wish to know why does base.clone does not work in .Net. In java if i do a
super.clone, it works fine. I have searched other newsgroups and was not
able find a reason for this behavior??

base.Clone doesn't work because Object doesn't provide a Clone method.
Instead, it provides Object.MemberwiseClone.
 

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