Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor in C#

Tags:

c#

constructor

I have a parent class with 2 constructor and the derived class trying to call the constructor of parent in 2 different methods

public class Parent
{
    public Parent()
    {
        //some stuffs
    }
    public Parent(string st)
    {
        //some stuffs
    }
}

Now I have a derived class with two methods. I Have to use Parent-constructor in one method and the Parent(string st) in other method. But here It is always calling the Parent-constructor. Below is the derived class

public class Derived : Parent
{
    public void GetData()
    {
        //Here I initialize the constructor like this
        Parent p = new Parent();
    }

    public void GetData1()
    {
        string s = "1";
        Parent p = new Parent(s);
    }
}

Please let me how to make this happen. Thanks in advance.

like image 311
Ram Avatar asked Dec 18 '25 20:12

Ram


1 Answers

Just have two constructors in your Derived class that use the appropriate constructor in the base.

public class Derived : Parent
{
   public Derived() : base()
   {
   }

   public Derived(string s) : base(s)
   {
   }
}

The :base() nomenclature will invoke the parent constructor.

like image 180
Steve Avatar answered Dec 20 '25 09:12

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!