Trevor Hickey Trevor Hickey - 1 month ago 8
C# Question

Can I construct composed classes without using 'new' so much?

I have a basic composition of types:

class A{
public A(B1 b1, B2 b2){
this.b1 = b1;
this.b2 = b2;
}
public B1 b1 {get; private set;}
public B2 b2 {get; private set;}
}

class B1{
public B1(C1 c1, C2 c2, C3 c3){
this.c1 = c1;
this.c2 = c2;
this.c3 = c3;
}
public C1 c1 {get; private set;}
public C2 c2 {get; private set;}
public C3 c3 {get; private set;}
}
class B2{
public B2(C1 c1, C2 c2, C3 c3){
this.c1 = c1;
this.c2 = c2;
this.c3 = c3;
}
public C1 c1 {get; private set;}
public C2 c2 {get; private set;}
public C3 c3 {get; private set;}
}

class C1{}
class C2{}
class C3{}


Is there a cleaner way to construct
A
?

public static void Main()
{
A a = new A(new B1(new C1(), new C2(), new C3()), new B2(new C1(), new C2(), new C3()));
}


Can I achieve the same construction without using
new
so much?

Is there something I can do to my constructors to make that possible?

Answer

If in the default constructor for A it created the new B's and in the default constructor for B it created the C's you could simplify it to just A a = new A();

class A{
    public A() : this(new B1(), new B2())
    {
    }

    public A(B1 b1, B2 b2){
        this.b1 = b1;
        this.b2 = b2;
    }
    public B1 b1 {get; private set;}
    public B2 b2 {get; private set;}
}

class B1{
    public B1() : this(new C1(), new C2(), new C3())
    {
    }

    public B1(C1 c1, C2 c2, C3 c3){
        this.c1 = c1;
        this.c2 = c2;
        this.c3 = c3;
    }
    public C1 c1 {get; private set;}
    public C2 c2 {get; private set;}
    public C3 c3 {get; private set;}
}
class B2{
    public B2() : this(new C1(), new C2(), new C3())
    {
    }

    public B2(C1 c1, C2 c2, C3 c3){
        this.c1 = c1;
        this.c2 = c2;
        this.c3 = c3;
    }
    public C1 c1 {get; private set;}
    public C2 c2 {get; private set;}
    public C3 c3 {get; private set;}
}

class C1{}
class C2{}
class C3{}

public static void Main()
{
    A a = new A();
}
Comments