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!!
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!!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With