Constructor chaining in conjunction with the base constructor invocation
Asked Answered
B

2

7

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?

Beebe answered 26/2, 2011 at 12:17 Comment(4)
What's wrong with just calling the other constructor overload from the constructor that accepts an additional parameter? this(s, n) instead of base(n, m)Tedi
I modified the question so that it reflects better what I currently have. I changed the types of the arguments of the overloaded base constructor.Beebe
Ah, very good. I didn't post that as an answer initially because I figured I was missing something obvious. Turns out that was indeed the case.Tedi
yea, sorry for the confusion before.Beebe
B
6

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) {}
Berceuse answered 26/2, 2011 at 12:24 Comment(2)
I modified the question so that it reflects better what I currently have. I changed the types of the arguments of the overloaded base constructor.Beebe
@Andreas Grech: In that case you can't even do what I suggested. There is no way to avoid repeating that code.Berceuse
S
0

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    
    }
}
Springing answered 26/2, 2011 at 12:22 Comment(1)
Ah no, that won't cut it; and besides, that looks like quite an ugly workaround, not to mention the fact that -1 may be a valid value in the 3-argument overloadBeebe

© 2022 - 2024 — McMap. All rights reserved.