how to clone a base class?

  • Thread starter Thread starter Amil Hanish
  • Start date Start date
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
}
}
 
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 ...
}
}
 
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 ...
}
}
 
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 ...
}
}
 
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.
 
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
 
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.
 
Back
Top