How to create an instance of a child instance from a parent instance

I am looking to create a child class using the parent instance in order to set all the inherited variables.

For instance:

public class Foo { //Variables } public class bar : Foo { public int ID { get; set; } public bar(Foo instance) { base = instance; // Doesn't work but is generally the idea I'm looking for } } 
+4
source share
4 answers

You will need to make all your members public within Foo , which you will need to install from the constructor. Then set the necessary properties.

0
source

Why can't you do this through the public auto property, as shown below. BTW, what you are trying to get is Composition , in which the bar object consists of the foo object. Not sure why you still inherit from foo ?

 public class bar : Foo { public int ID { get; set; } public Foo baseinstance { get; set;} public bar(Foo instance) { baseinstance = instance; } } 

I'm not quite sure, but from your published code (in particular, below) it seems that you are trying to call the base class constructor initializer or constructor initializer , as you said

I am looking to get a child class created using the parent instance to set all the inherited variables.

 public bar(Foo instance) { base = instance; } 

In fact, it should be

 public bar(Foo instance) : base() { //child instance initialization } 

But what is not required for a constructor without parameters occurs when you create an instance of the constructor of the constructor of children, which will be called, and the base class will be initialized first in order to initialize the base element before the child is initialized.

If you have a parameterized constructor in the database and in the descendant, you can explicitly call the database constructor

0
source

I think you are looking for some kind of cartographer that maps from one object to another.

You can use an open source project like AutoMapper or ValueInjecter , which can be found on NuGet .

Here is also a good article: Copy values ​​from one object to another

Demo with ValueInjecter :

 static void Main(string[] args) { var foo = new Foo() { Property1 = "Value1", Property2 = "Value2" }; var bar = Mapper.Map<Bar>(foo); bar.Id = 3; Console.WriteLine(bar.Id); //3 Console.WriteLine(bar.Property1); //Value1 Console.WriteLine(bar.Property2); //Value2 } 
0
source

Just add the constructor to the parent class Foo , which takes an instance of Foo and takes care of copying the fields. The Bar class can then call it as a base constructor.

 public class Foo { private string var1; private string var2; public Foo() { } public Foo(Foo otherFoo) { this.var1 = otherFoo.var1; this.var2 = otherFoo.var2; } } public class Bar : Foo { public int ID { get; set; } public Bar(Foo instance) : base(instance) { } } 
0
source

All Articles