Inheritance: possible to change base reference to something else?
- by fred
For example I have two classes, Base and Derived as shown below:
class Base
{
public string Name { get; set; }
public Base()
{
}
}
class Derived : Base
{
public Derived(Base b)
{
base = b; // doesn't compile, but is there any way to do something similar?
}
}
So that they behave like this:
Base b = new Base();
b.Name = "Bob";
Derived d = new Derived(b);
d.Name = "John";
// b.Name is now "John" also
Is this possible? I guess one way would be to keep the Base b reference in Derived and override Derived.Name to point to b.Name? Is there an easier way though, for example if I have like 50 properties to override?
class Derived : Base
{
Base b;
public override string Name
{
get { return b.Name; }
set { b.Name = value; }
}
public Derived(Base b)
{
this.b = b;
}
}