Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

quick constructor question

Status
Not open for further replies.

misterstick

Programmer
Apr 7, 2000
633
GB
class a derives from class b. if i have an instance of class b, is there a quick way to construct an instance of class a, without hard-coding all the attributes?

Code:
public class B
{
 public B() { }

 // properties galore
 private string p1; public string P1 { get; set; } //...
}

public class A : B
{
 public A(B b)
 {
  // how do i get the properties of b into my
  // new instance of a?
 }
}


mr s. <;)

 
I would do it this way
Code:
public class A : B
{
 public A(B b)
 {
   this.Property1 = b.Property1;
   this.Property2 = b.Property2;
   ...
 }
}
I haven't worked with reflection, but there may be something there which would help.

another option: Have B and A inherit a common interface. the cast B to A.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
looks like the answer is "you can't", then,

i was hoping for something like this:

Code:
public class A : B
{
 public A(B b) : b.Clone()
 {

 }
}

but i guess that's just dumb.

i've decided to refactor so that A exposes a reference to a B instance, which is much easier, if not quite so tidy.

Code:
public class A
{
 public A(B p)
 {
  b = p;
 }

 private readonly B b;
 public B B { get { return b; } }
}

many thanks,


mr s. <;)

 
I guess I'm a little late, but you might want to take a look at this blog entry that illustrates creating an "intelligent" copy constructor using reflection. You could just implement it for the child class and change the access restrictions on the parent class memeber variables from "private" to "protected". That should do what you're looking for.
 
because the relationship between A and B is "IS_A_RELATIONSHIP", you can use implicit casting:
Code:
B b = new B();
A a = new A();
// codes here to initialize b parameters and proberties
a = b; // you also use a = (a)b;
// codes here to initialize other params of a

Touraj Ebrahimi
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top