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
No the syntax you are trying is not possible in C# .NET you need to do.
Why would you need to? By declaring a new B, the CLR automatically calls the constructors for both classes.
B new has the fields of both classes. However, you should declare them with an initializer unless you like nulls:
Unfortunately
base
is readonly.[Edit]
Well perhaps not so unfortunate. The relationship between a base class and a child class is
IS-A
notHAS-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-A
base 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.
Wrong question. You're obviously abusing inheritance here. Try to refactor it, so that you keep a reference to A as a member field. If you need polymorphism, consider having common base class or better yet - an interface.
Is the intent that these fields will be initialized once during object construction, or could "Assign" be called multiple times during an object's lifetime? If the latter, you can disregard the rest of this :)
Andrew's distinction between IS-A and HAS-A is an important one; if the relationship really is a HAS-A, his composition solution is the way to go.
If an IS-A relationship makes more sense (and you are able to modify A), a copy constructor might be a good idea:
You end up having to copy each of A's properties, but the responsibility for doing so resides in A where it belongs.