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
Unfortunately
baseis readonly.[Edit]
Well perhaps not so unfortunate. The relationship between a base class and a child class is
IS-AnotHAS-A. By allowing a child class to change the instance of the base class you are allowing the child class to change its own reference since itIS-Abase class. If you truly need this functionality then I would suggest you change your inheritance model to reflect what you truly want to do.Something like this:
seems more appropriate and has clearer meaning and functionality.