Initialize base class in .NET
Unfortunately base
is readonly.
[Edit]
Well perhaps not so unfortunate. The relationship between a base class and a child class is IS-A
not HAS-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 it IS-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:
public class A
{
public string field1;
public string field2;
}
public class B
{
public string field3;
public A a;
public void Assign(A source)
{
this.a = source;
}
}
seems more appropriate and has clearer meaning and functionality.
While there are many excellent answers here, I think the proper way to do this is by chaining the constructors:
public class A
{
public string field1;
public string field2;
public A(string field1, string2 field2)
{
this.field1 = field1;
this.field2 = field2;
}
}
public class B : A
{
public string field3;
public B(string field1, string2 field2, string field3)
: base(field1, field2)
{
this.field3 = field3;
}
}
public Assign(A a)
{
foreach (var prop in typeof(A).GetProperties())
{
this.GetType().GetProperty(prop.Name).SetValue(this, prop.GetValue(a, null),null);
}
}
Basically, it uses reflection to get all the properties of the base and assign the values of this, to all the values that exist in A.
EDIT: To all you naysayers out there, I quickly tested this now with a base class that had 100 integer variables. I then had this assign method in a subclass. It took 46 milliseconds to run. I don't know about you, but I'm totally fine with that.
No, the syntax you are trying is not possible. In C# .NET you need to do:
public void Assign(A source) {
field1 = source.field1;
field2 = source.field2;
}