1
\$\begingroup\$

I am getting object of a class AAA from somewhere and I want to add more information in that object. So, I am creating a new class BBB which is derived from AAA. The class BBB has additional field dictionary. I am populating this dictionary in derived class constructor which is taking the Class AAA object and array of item which I want to use as keys of dictionary and values of this dictionary are elements of a field of object of class AAA. I tried to create similar scenario in blow example code:

void Main(){    
     A obj = new A () ;
     obj.prop1 =  new int [] {5 ,10, 15}   ;
     obj.prop2 =  "Hello" ;
     obj.prop3 = "World" ;
//   obj.Dump () ;
     B obj2 = new B (new int [] {1,2,3}, obj)  ;     
//   obj2.Dump () ;

}

// Define other methods and classes here
public class A {
    public int [] prop1 ;
    public string prop2 ;
    public string prop3 ;
}

public class B : A {
    public Dictionary <int, int> prop4 ;
    public B (int [] keys, A a) {
    prop4 = new Dictionary <int, int> () ;
        if (keys.Length == a.prop1.Length ) {
            for (int i = 0 ; i < keys.Length ; i++ ) {
                prop4.Add (keys[i], a.prop1[i]) ;
            }
            // is there a way to obsolete below lines of code???
            this.prop1 = a.prop1 ; 
            this.prop2 = a.prop2 ;
            this.prop3 = a.prop3 ;
        }
        else {
            throw new Exception ("something wrong") ;
        }           
    }
}

In derived class constructor, I am filling the properties manually and I do not want to do it. Is there another way to do it. I have more than 20 properties in my actual class.

\$\endgroup\$
  • \$\begingroup\$ Can you modify A? Does the real A have a constructor (apart from the parameterless one). \$\endgroup\$ – svick Oct 22 '13 at 17:30
1
\$\begingroup\$

Those lines are managing the properties of A, so they belong in A. I've added a protected copy constructor and used constructor chaining to solve your issue:

public class A
{
  public int [] prop1 ;
  public string prop2 ;
  public string prop3 ;

  public A() {}

  protected A(A a)  //copy constructor
  {
    this.prop1 = a.prop1 ;  //review: should this reference be copied, or a new copy made?
    this.prop2 = a.prop2 ;
    this.prop3 = a.prop3 ;
  }
}

public class B : A
{
  public Dictionary <int, int> prop4 ;

  public B (int [] keys, A a) : base(a)  //constructor chaining
  {
    prop4 = new Dictionary <int, int> () ;
    if (keys.Length == a.prop1.Length )
    {
      for (int i = 0 ; i < keys.Length ; i++ )
      {
        prop4.Add (keys[i], a.prop1[i]) ;
      }
    }
    else
    {
      throw new Exception ("something wrong") ;
    }           
  }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.