cdeszaq
cdeszaq

Reputation: 31320

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

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.

Upvotes: 6

Views: 7801

Answers (2)

David Ly
David Ly

Reputation: 31606

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

Upvotes: 4

cdeszaq
cdeszaq

Reputation: 31320

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.

Upvotes: 2

Related Questions