Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor chaining in conjunction with the base constructor invocation

Say I have the following:

class Base {
    public Base (int n) { }
    public Base (Object1 n, Object2 m) { }
}

class Derived : Base {

    string S;

    public Derived (string s, int n) : base(n) {
        S = s;
    }

    public Derived (string s, Object1 n, Object2 m) : base(n, m) {
        S = s; // repeated
    }
}

Notice how I need formal argument n in both overloads of the Derived and thus I have to repeat the N = n; line.

Now I know that this can be encapsulated into a separate method but you still need the same two method calls from both overloads. So, is there a more 'elegant' way of doing this, maybe by using this in conjunction with base?

This is so that I can have a have a private constructor taking one argument s and the other two overloads can call that one...or is this maybe just the same as having a separate private method?

like image 440
Andreas Grech Avatar asked Feb 26 '11 12:02

Andreas Grech


1 Answers

There is no ideal solution for that. There is a way to avoid repeating the code in the Derived constructors, but then you have to repeat the default value of the m parameter:

public Derived (string s, int n) : this(s, n, 0) {}
like image 155
Guffa Avatar answered Sep 30 '22 09:09

Guffa