Alex Rivera | Logout

Initialize base class in .NET

Asked 2009-01-29T18:41:12.690
10

How do I go about if I need to initialize an object's base with existing object? For example, in this scenario:

public class A
{
    public string field1;
    public string field2;
}

public class B : A
{
    public string field3;
    public void Assign(A source)
    {
        this.base = source; // <-- will not work, what can I do here?
    }
}

Assign() method can, obviously assign values to the base class field-by-field, but isn't there a better solution? Since class B inherits from A, there must be a way to just assign A to the B.base

In C++ this would be a trivial thing to do, but I can't seem to grasp how to do this in .NET

Edit
Report

1 Answer

1

I hope I'm not the only one who thinks swapping out your base class is a bad design pattern. Another approach is to replace inheritance with composition:

public class A
{
    public string Field1 { get; set; }
    public string Field2 { get; set; }
}

public class B
{
    public A A { get; set; }
    public string Field3 { get; set; }

    public B(A a) { this.A = a; }
}

Now its trivial to write something like this:

B b = new B ( new A { Field1 = "hello", Field2 = "world" } );

b.A = new A { Field1 = "hola", Field2 = "luna" };
answered 2009-01-29T19:09:58.250

Your Answer