title: How to design inheritance for multilevel composition classes
body: <p>I have to solve a quite tricky problem and I will try my best to explain the problem. I have a complicated object and it has two level composition and somehow I am supposed to define two classes for low level of composition and reflect the new types at higher level. In order to reflect the changes in low composition, I am defining two classes in higher levels as well. </p>
  
  <p>I am using abstract factory approach to create instances of higher level classes. All classes are serializable.</p>
  
  <p>C in below diagram is correspond to higher level classes and A is correspond to low level classes. Object of A classes are composed of objects of level 2 classes  and they are composed of object of C classes.</p>
  
  <p>In abstract factory approach, I am trying to deserialize the object and return as parent class. I am getting casting related error. However, I think there is some fundamental problem in design which I am unable to figure out. I know parent object can not be casted as child object.</p>
  
  <p><a href="https://i.stack.imgur.com/FCXRi.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FCXRi.gif" alt="enter image description here"></a></p>
  
  <pre><code>public class A {
      public virtual Double [] Prop1 { get; set; }
      public virtual Double [] Prop2 { get; set; }
    }
  
  
    public class A1 : A {
      public override double[ ] Prop1 {
        get {
          // implementation other than base class
        }
  
        set {
          // implementation other than base class
        }
      }
  
    }
  
  
    public class A2 : A {
      public override double[ ] Prop2 {
        get {
          // implementation other than base class
        }
  
        set {
          // implementation other than base class
        }
      }
    }
  
  
    public class B {
      public virtual A A_obj { get; set; }
    }
  
  
    public class B1 : B {
  
      public override A A_obj {
        get {
          // want to retun the object of A1
        }
  
        set {
          // want to handle the object A1
        }
      }
    }
  
  
    public class B2 : B {
      public override A A_obj {
        get {
          // want to retun the object of A2
        }
  
        set {
          // want to handle the object A2
        }
      }
    }
  
  
    public class C {
      public virtual B [] B_obj { get; set; }
  
    }
  
    public class C1 : C {
      public override B[ ] B_obj {
        get {
          // want to retun the object of B1
        }
  
        set {
          // want to handle the object B1
        }
      }
    }
  
    public class C2 : C {
      public override B[ ] B_obj {
        get {
          // want to retun the object of B2
        }
  
        set {
          // want to handle the object B2
        }
      }
    }
  </code></pre>