Inheritance: possible to change base reference to something else?

Posted by fred on Stack Overflow See other posts from Stack Overflow or by fred
Published on 2011-11-17T01:31:25Z Indexed on 2011/11/17 1:50 UTC
Read the original article Hit count: 155

Filed under:
|

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;
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET