| re: To Clone or Not To Clone?
Hi Bruce,
Yip i though that this was the way to go myself but then i did a test
probram where my base class didn't use reflection for clone.
Results were amazing in that this works!
public override object Clone() // derived clone method
{
DerivedTextBox tb = (DerivedTextBox)base.Clone();
tb.MaxValue = this.MaxValue;
tb.MinValue = this.MinValue;
return tb;
}
basically it appears that if implemented this way things it works.
However if i tried to do that outside the class. i.e.
void Main()
{
BaseTextBox tbb = new BaseTextBox();
DerivedTextBox tbd = (DerivedTextBox)tbb.Clone(); // exception thrown
}
So I'm thinking i need to trawl through the language spec or the CLR spec to
find where they say that this is how using base clone works.
Thanks
Brian
"Bruce Wood" wrote:
[color=blue]
> It really depends upon how smart the base class's Clone is. If it
> simply instantiates a base object, then your cast will fail when you
> try to assign it to "tb". If the base class's Clone method is clever
> and uses reflection to decide what to instantiate, it may work.
>
> As an aside, this is why I implement Clone within my own classes as
> Clone plus CopyTo: then I override like this:
>
> public override DerivedClass Clone()
> {
> DerivedClass obj = new DerivedClass();
> this.CopyTo(obj);
> return obj;
> }
>
> protected override void CopyTo(BaseClass other)
> {
> base.CopyTo(other);
> DerivedClass otherDerived = (DerivedClass)other;
> otherDerived._field1 = this._field1;
> ... etc ...
> }
>
> However, if you don't have control over the base class, then you can't
> do this.
>
>[/color] |