1

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.

scorch855
  • 302
  • 1
  • 9
  • Does this answer your question? [cast the Parent object to Child object in C#](https://stackoverflow.com/questions/9885644/cast-the-parent-object-to-child-object-in-c-sharp) – Michael Johnston May 20 '20 at 01:31
  • 1
    `B` is more specific than `A` so `A` cannot be cast to `B`. I also have absolutely no idea what you're trying to achieve. – CodingYoshi May 20 '20 at 01:51
  • Yeah I realised shortly after I posted that all the options I provided are are invalid. Yes I have seen that question, it's the reason for the "Without using reflection" bit. If I don't get any alternatives then I will either delete this question or link to that answer and mark it as answered. Thanks – scorch855 May 20 '20 at 02:09

0 Answers0