I have a parent class with many properties so having a giant constructor in the child would be a pain to write and maintain. Is there a good way of doing this without using reflection? It seems like this is something which should be possible.
public class A
{
public int Property1 { get; set; }
public A(int property1)
{
Property1 = property1;
}
}
public class B : A
{
public bool Property2 { get; set; }
public B() { }
public B(A parent, bool property2)
{
//This call fails because the object doesn't exist. (I think it would also be read-only anyway?)
this = (B) parent;
Property2 = property2;
}
//I'm trying to avoid this
public void SetNewProperties(bool property2)
{
Property2 = property2;
}
}
//Writing a whole extension class seems excessive (and more difficult to maintain)
public static class BExtensions
{
public static B ConvertToB(this A parent, bool, property2)
{
B child = (A) parent;
child.Property2 = property2;
return child;
}
}
//Called this this
A instance1 = new A(5);
B instance2 = new B(instance1, true);
//Instead of this
A instance1 = new A(5);
B instance2 = (A) instance1;
instance2.SetNewProperties(true);
//Or
A instance1 = new A(5);
B instance2 = instance1.ConvertToB(true);
I know I could also create a ConvertTo()
method in the parent but it's already bloated and it just generally seems like a bad place to put it.