-2

let's say we have two classes

class baseClass
{
    public baseClass()
    {

    }
    public baseClass(int value)
    {

    }
}

class derivedClass
{

}

is there a way to call the parametrized constructor from derivedClass like

derivedClass instance = new derivedClass(1)

without implmenting a constructor in derivedClass which cals base(value)

2
  • 2
    "...without implmenting a constructor in derivedClass..." No. In order to pass arguments to a constructor you need to make a constructor. Commented Aug 9, 2021 at 20:15
  • If there was an auto-passthrough of those parameters, then you would need special syntax to prevent that when you don't want it. Commented Aug 9, 2021 at 20:17

1 Answer 1

-1

Are you looking for something along the lines of

   class BaseClass
   {
      public BaseClass()
      {

      }
      public BaseClass(int value)
      {

      }
   }

   class DerivedClass : BaseClass
   {
      public DerivedClass(int value) : base(value)
      {

      }
   }

Which allows you to call :

DerivedClass test = new DerivedClass(2);
Sign up to request clarification or add additional context in comments.

4 Comments

i know this kind of solution but i wonder if there is any solution where i do not need this part : public DerivedClass(int value) : base(value) { } in any derived class
@NeoPrince No, you have to define constructors you want in the child class to propagate what you want. Take a look for example at geeksforgeeks.org/c-sharp-inheritance-in-constructors and C# MSDoc
OP said, without implmenting a constructor in derivedClass... this is the exact opposite.
Unless you call the base(value) inside of one of your derived constructors, I don't think you can. The BaseClass constructor can't define the DerivedClass instance.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.