Cloning subclasses. How does casting to a derived class work?

  • Thread starter Thread starter Heinz Kiosk
  • Start date Start date
H

Heinz Kiosk

A piece of code generated by an MS wizard goes as follows:

public class MyDataTable : DataTable...
{
....
public override DataTable Clone()
{
MyDataTable cln = ((MyDataTable)(base.Clone())); // What is going on here?
cln.InitVars();
return cln;
}
....
}

MyDataTable is derived from DataTable. How does casting a DataTable to a
MyDataTable in the commented line work? I must be missing some rules about
how casting works in .NET. If you cast to a derived class does the compiler
fill in defaults for derived members or use the derived constructor and then
do a field-by-field copy or what? Something clever must be going on.

Thank you.

Tom
 
Heinz Kiosk said:
A piece of code generated by an MS wizard goes as follows:

public class MyDataTable : DataTable...
{
...
public override DataTable Clone()
{
MyDataTable cln = ((MyDataTable)(base.Clone())); // What is going on here?
cln.InitVars();
return cln;
}
...
}

MyDataTable is derived from DataTable. How does casting a DataTable to a
MyDataTable in the commented line work? I must be missing some rules about
how casting works in .NET. If you cast to a derived class does the compiler
fill in defaults for derived members or use the derived constructor and then
do a field-by-field copy or what? Something clever must be going on.

base.Clone() is actually returning a reference to a MyDataTable object
- at least if it's working according to the documentation. It's
probably using object.MemberwiseCopy() - have a look at the description
for that method for more information. Hope that explains what's going
on - let me know if you have any more concerns.
 
Jon Skeet said:
base.Clone() is actually returning a reference to a MyDataTable object
- at least if it's working according to the documentation. It's
probably using object.MemberwiseCopy() - have a look at the description
for that method for more information. Hope that explains what's going
on - let me know if you have any more concerns.

Thanks for that jon, the implementation of Clone is so alien to my 10 years
of C++ experience that I somehow missed the comment about subclasses in the
documentation, because I would just have viewed that as impossible.... These
classes that know all about their storage and implementation and the storage
etc derivations take some getting used to. Presumably the ability to clone
controls works similarly.

Thanks

Tom
 
Back
Top