1

Say you have a parent class with lots of subclasses. If the constructor of the parent gets a new parameter you would have to change all the children constructors, too. Is there a way to inherit the parent constructor without naming all the parameters?

Code that I want to write, but gives the error 'There is no argument given for the formal parameter...':

public abstract class A
{
    public A(someType somePar)
    {
    }
}

public class B : A
{
}

Annoying solution:

public abstract class A
{
    public A(someType somePar)
    {
    }
}

public class B : A
{ 
   //If there is a new parameter, this would need to change
   B(someType somePar) : base(somePar)
   {
   }
}

Sorry if there is an obvious solution to this, I'm writing for the first time with C#

9
  • 2
    Optional arguments Commented Aug 21, 2021 at 8:54
  • 2
    Have your base class take a specific class as a parameter (rather than say a string or an int) with all of the parameters instead as properties of the class.. If you add a new property to the class, you don't need to change anything in terms of the base calls. Commented Aug 21, 2021 at 8:55
  • 1
    And when mjwills says "specific class" they don't mean one of the concrete subclasses but some other class that's just a holder for data that an A or B can use during construction. Kinda like a ProcessStartInfo is a holder for info that is used by the Process.Start method. Microsoft could add a property to ProcessStartInfo without needing to change the signature of Process.Start method Commented Aug 21, 2021 at 9:04
  • 1
    Does this answer your question? C# does not inherit the constructor from base class and How to inherit constructors? and Can I inherit constructors? Commented Aug 21, 2021 at 9:06
  • 2
    Yeah, I think I understand it now. Thanks for all your answers. Commented Aug 21, 2021 at 9:08

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.