Constructor chaining in conjunction with the base constructor invocation

1.6k views Asked by At

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?

2

There are 2 answers

2
Guffa On BEST ANSWER

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) {}
1
John Arlen On

Only a slight improvement, but...

class Derived : Base
{
    string S;
    public Derived(string s, int n) : this(s,n,-1)
    {
    }

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