-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
    "...without implmenting a constructor in derivedClass..." No. In order to pass arguments to a constructor you need to make a constructor. – gunr2171 Aug 09 '21 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. – Hans Kesting Aug 09 '21 at 20:17

1 Answers1

-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);
Azazel
  • 11
  • 1
  • 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 Aug 09 '21 at 20:14
  • 1
    @NeoPrince No, you have to define constructors you want in the child class to propagate what you want. Take a look for example at https://www.geeksforgeeks.org/c-sharp-inheritance-in-constructors/ and [C# MSDoc](https://learn.microsoft.com/dotnet/csharp) –  Aug 09 '21 at 20:15
  • 1
    OP said, `without implmenting a constructor in derivedClass`... this is the exact opposite. – Trevor Aug 09 '21 at 20:16
  • 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. – Azazel Aug 09 '21 at 20:19