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?
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) {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With