Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Call base and class constructors in derived class

Suppose I have the following base and derived class in my C# program:

class BaseClass
{
    public BaseClass() { }
    public BaseClass(int someVal) 
    { 
        // do something here 
    }
}

class DerivedClass : BaseClass
{
    public DerivedClass(string somethingNew) 
        : base()
    {
        // do something with the somethingNew varible
    }
    public DerivedClass(string somethingNew, int someVal)
        : base(someVal)
    {
        // do **THE SAME THING** with the somethingNew varible as in first constructor
    }
}

My question comes about in the final constructor - Ideally, what I'd like is to be able to do something along the lines of (although this won't compile):

    public DerivedClass(string somethingNew, int someVal)
        : base(someVal)
        : this(somethingNew)
    {

    }

In other words, call both the base and the first constructor.

Is there any way to do this or do I just need to re-write the code inside each constructor in this case?

Thanks!!

like image 512
John Bustos Avatar asked Sep 01 '25 17:09

John Bustos


1 Answers

Not to say this is the CORRECT answer (and I'd love to hear how others would recommend I do this), but what I ended up doing was creating a private setter method that either constructor can call along the following lines:

class DerivedClass : BaseClass
{
    public DerivedClass(string somethingNew) 
        : base()
    {
        setVals(somethingNew);
    }
    public DerivedClass(string somethingNew, int someVal)
        : base(someVal)
    {
        setVals(somethingNew);
    }

    private setVals(string somethingNew) 
    {
        // do something with the somethingNew varible
    }
}

It saved my issue of having to deal with repetitive code and seems to be the cleanest way to do this, but, as I said, I'd love to see what others recommend / if there's a way to do this better.

Thanks!!!

like image 66
John Bustos Avatar answered Sep 04 '25 06:09

John Bustos