Cast from base class to a derived class

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Casting from a DataSet to a typed DataSet seems to work, as in the example
below. This seems counterintuitive to me - isn't it attempting to cast from
a base class to a derived class? How does this magic work?

MyTypedDataSet typedDataSet;
// ... fill the typed DataSet with some data

// Serailize
typedDataSet.WriteXml("filename.dat");

// Deserialize into an untyped DataSet
DataSet ds = new DataSet();
ds.ReadXml("filename.dat");

// I wouldn't expect this to work
MyTypedDataSet newTypedDataSet = (MyTypedDataSet) ds;
 
Since neither the DataSet or the TypedDataSet contain any user defined
conversions - this is not possible unless one has been added to the
TypedDataSet generated code.

The example you provided does not compile for me because the typedDataSet
variable is never assigned a value.
If I fix this problem, I get a runtime cast exception when trying to assign
the dataset instance to the TypedDataSet reference.

Andrew Conrad
Microsoft Corp
 
Back
Top