By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,786 Members | 2,241 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 428,786 IT Pros & Developers. It's quick & easy.

Inclass conversion from base class to derived class

P: 5
Hello everybody!

My problem is somewhat strange since I can't think of any normal situation where one would like to do what I need, but here it goes. I need to somehow cast a base class to a derived class, but from the base-class code. I would need to do something like this:

Expand|Select|Wrap|Line Numbers
  1. class Base
  2. {
  3.     public Base() { }
  4.     public void Convert()
  5.     {
  6.         this = new Derived(); 
  7.         // this, of course, doesn't work
  8.     }
  9. }
  10. class Derived : Base
  11. {
  12.     public Derived() { }
  13. }
  14.  
Now, the reason I need to do this is because I need to serialize a list that contains the Base class type objects, but I don't know what do the derived classes look like. All I know is that they have a parameter-less constructor, their full names and the DLL they are in. This gives me the possibility to use the Activator function and fill my list up. But I cannot write the functions for the base class that the IXmlSerializable interface demands because to do so I must initialize the base class as a derived class of a specific type, but within the base class itself. I do know that I can use wrappers for the data, and then fill the list using the Activator class, but since I use the base class extensively throughout my project, it would be a tough thing to do..

So, any suggestions are more than welcome.
Mar 29 '10 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.