I currently have a derived class and a base class. How can I make the base class of the derived class equal to a base class that I have? Will a shallow copy work?
I realize that a couple of other answers may have touched on this solution, but I wanted to spell it out more completely.
The solution I found was to populate the base class, then pass that base class into the constructor of the derived class. The constructor of the derived class populates its fields based on the base class.
class Base
{
private string name;
public string Name { get; set; }
private string address;
public string Address { get; set; }
}
class Derived:Base
{
Derived(Base toCopy)
{
this.Name = toCopy.Name;
this.Address = toCopy.Address;
}
private string field;
public String field { get; set; }
}
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Base b = new Base();
b.Address = "Iliff";
b.Name = "somename";
//You are now passing the base class into the constructor of the derived class.
Derived d = new Derived(b);
}
}
}