Cast from base class to a derived class

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;
 
A

Andrew Conrad

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
 

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