Constructor chain combined with calling the base constructor

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 the formal argument n in both Derived overloads and therefore I need to repeat the line N = n; .

Now I know that this can be encapsulated in a separate method, but you still need the same calls from both overloads. So, is there a more β€œelegant” way to do this, perhaps using this in combination with base ?

Is it that I can have a private constructor that takes one argument s , and the other two overloads can cause this ... or can it be just the same as a separate private method?

+6
inheritance c # constructor-chaining
source share
2 answers

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

 public Derived (string s, int n) : this(s, n, 0) {} 
+5
source share

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 } } 
0
source share

All Articles