I have a parent class that has an overloaded constructor, and I have a subclass that has a constructor with optional parameters. Is there a way to have the subclass's constructors still expose the overloaded-ness of the parent class while preserving it's own optional parameters?
Here's some example code of the two classes and their required constructors:
class Foo {
Foo(String arg0)
{
// do some stuff with arg0
}
Foo(String arg0, List<x> arg1)
: this(arg0)
{
// do some other stuff with arg1 that is special because we have an arg1
}
}
class Bar : Foo {
Bar(String arg0, List<y> arg2 = null, String arg3 = "")
: base(arg0)
{
// some third thing with arg2 and arg3
}
}
This is the method signature for the other subclass constructor I would like to also have to expose the overload of the parent constructor, but the question is how to do it:
Bar(String arg0, List<x> arg1, List<y> arg2 = null, String arg3 = "")
I have, I think, found a solution, but I am not sure it is as clean as it could be. I have posted it as an answer just in case it is the only option.
<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .
These are the type of operators that act upon just a single operand for producing a new value. All the unary operators have equal precedence, and their associativity is from right to left. When we combine the unary operator with an operand, we get the unary expression.
If you can change Foo
to only have one constructor with an optional parameter you can do the following:
public class Foo
{
public Foo(String arg0, List<x> arg1 = null)
{
// do some stuff with arg0
if (arg1 != null)
{
// do some other stuff with arg1
}
}
}
public class Bar : Foo
{
public Bar(String arg0, List<x> arg1 = null, List<y> arg2 = null, String arg3 = "")
: base(arg0, arg1)
{
// some third thing with arg2 and arg3
}
}
Here is the solution I have come up with:
class Foo {
Foo(String arg0)
{
// do some stuff with arg0
}
Foo(String arg0, List<x> arg1)
: this(arg0)
{
// do some other stuff with arg1
}
}
class Bar : Foo {
Bar(String arg0, List<y> arg2 = null, String arg3 = "")
: base(arg0)
{
this.Initialize( arg2, arg3);
}
Bar(String arg0, List<x> arg1, List<y> arg2 = null, String arg3 = "")
: base(arg0, arg1)
{
this.Initialize( arg2, arg3);
}
private void Initialize(List<y> arg2, String arg3)
{
// some third thing with arg2 and arg3
}
}
It seems a bit unclean because I am not chaining the subclass's constructors together and am calling a function instead, but I can't figure out any other way to do this.
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