In C# 4, how can I have constructors with optional parameters in a subclass of a parent with an overloaded constructor?

cdeszaq picture cdeszaq · May 6, 2011 · Viewed 7.7k times · Source

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.

Answer

Davy8 picture Davy8 · May 6, 2011

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
    }
}