Search code examples
c#inheritanceclone

Less code for load and save methods in derived classes by using base class methods but without downcasting


I'm trying to simplify load and save methods for several classes which are basically the base class with a few new fields. All derived classes make use of all base class' fields, so their load/save methods include the load/save code of the base class with an addition of some lines for taking care of the derived classes' remaining unhandled fields.

My first thought was I could just load an instance as a base class, downcast to derived class and continue loading the remaining fields, but apparently you can't just downcast to a derived class in C#. After some thinking I thought maybe I could iterate through all field members of the base class and copy over those field values to a new instance of derived class, but I'm not sure this is the best (or the fastest) way to do this.

Basically what I'd like to do is to load an instance of a base class, cast it to derived class, and then finish loading the remaining fields.

Is there some way to save the same lines of code in Load and Save methods of derived classes, which include all the Load and Save code from the base class without downcasting?

Here's some example code (the real thing is just a few times longer):

class Base 
{
    int i;
    static Base Load(Dictionary<string, object> dic)
    {
        Base b = new Base();
        b.i = (int)dic["i"];
        return b;
    }
}
class Derived : Base
{
    float f;
    static Derived Load(Dictionary<string, object> dic)
    {
        Derived d = new Derived();
        d.i = (int)dic["i"];
        d.f = (float)dic["f"];
        return d;
    }
}

Solution

  • I think you are looking for regular serialization code:

     class Base 
     {  
         public int Field1 {get;set;}
         virtual void Load(BinaryReader reader)
         {
             Field1 = reader.ReadInt();
         }
     }
     class Derived:Base
     {  
         public int Field2 {get;set;}
         override void Load(BinaryReader reader)
         {
             base.Load(reader);
             Field2 = reader.ReadInt();
         }
     }
    

    With usage similar to:

     Base toRead = new Derived();
     toRead.Load(reader);