I have a chain of inheritance and want to get a base class instance. The code looks like this:
[Serializable()]
class MyBaseClass {
public MyBaseClass() { /* Ctor implementation */}
public MyBaseClass( someVar ) { /* Ctor implementation */}
public MyBaseClass GetBaseInstance{ return( (MyBaseClass)this ); }
// Base class methods & properties
}
class Level1Class : MyBaseClass {
// Some methods
// Some properties
// Some objects
}
class Level2Class : Level1Class {
// Some more methods
// Some more properties
// Some more objects
}
At some point in my code I have access to an instance of Level2Class but I need to get an instance from MyBaseClass. I need a strict MyBaseClass instance since I (try to) feed that instance to an XML serializer. The XML serialization is defined for MyBaseClass but not for Level1Class and Level2Class.
I tried a couple of things:
var TheInstance = Level2ClassInstance as MyBaseClass; // return a Level2Class instance
var TheInstance = Level2ClassInstance.GetBase(); // return a Level2Class instance
// The serializer code
FileInfo fobject = new FileInfo( "MyXMLFile.xml" );
XmlSerializer MySerializer = new XmlSerializer( TheInstance.GetType() );
using( StreamWriter xmlStream = new StreamWriter( fobject.FullName ) ) {
MySerializer.Serialize( xmlStream, TheInstance );
}
I guess I am missing out on something obvious... In this situation how can I get an instance of MyBaseClass? Is it required to implement copy constructors for every class?
Any pointers would be greatly appreciated...
Edit 1: I added the serializer code. I also found out that in Level2Class and Level1Class some types of objects give problems. In particular Generic dictionaries. I found a work around by making Level1Class & Level2Class serialisable (using [Serializable()]) and then explicitely ignore the dictionaries (using [XmlIgnore]). This works but has a downsides: The XML file now contains the class type Level2Class (with the content of MyBaseClass).