Ben Ben - 4 months ago 9
C# Question

How can I allow a child class to call one of multiple base constructors with the same signatures?

I have a parent class in C# that contains several constructors. Some of them have the same signatures, like so.

public MyClass()
{
//Do something
}

public MyClass()
{
//Do something else
}


How can I allow a child class to choose only one of these constructors to use as a base?

Answer

In C# it is not possible to have multiple constructors with the same signature within a single class. Why don't you simply implement multiple protected methods - each method with its own specific name and then call the desired method from the child's constructor? Something like this:

public class MyClass
{
    protected Foo()
    {
        // Do something
    }

    protected Bar()
    {
        // Do something else
    }
}

public class MyChildClass : MyClass
{
    public MyChildClass(int x)
    {
        if(x > 0)
        {
            Foo();
        }
        else
        {
            Bar();
        }
    }
}

Update

Based on the additional information provided in the comments I am adding one more possible solution that may be a better fit for your case:

public class MyGrandClass
{
    public MyGrandClass(string name)
    {
        // Do something with the name.
    }

    public MyGrandClass()
    {
        // Do something else.
    }
}

public class MyClass : MyGrandClass
{
    public MyClass(string name) : base(name)
    {
    }

    public MyClass()
    {
    }
}

public class MyChildClass : MyClass
{
    public MyChildClass(string name) : base(name)
    {
    }

    public MyChildClass()
    {
    }
}