Let's say I have the following constructors for Foo in C#:
public Foo()
{
// ...
}
protected Foo(bool connect)
: this()
{
// ...
}
I am searching for a way to only execute the this() part whenever the connect parameter is true. Is these a way to do this?
(For curious people: The reasoning behind this is that the Foo class creates objects that connect to certain things; when they are created, they should always try to connect as well. Right now, I am creating an emulator (or MOCK) for it which extends the Foo class. That's what I'm adding the protected constructor for; when this one is used, there should be the option to not create an actual connection. I want to implement this while changing the Foo class as little as possible.)
No, you cannot call this() conditionally in that way. However, you can move the conditional code to the protected contructor and just call that constructor from the public one:
public Foo() : this(true)
{
}
protected Foo(bool connect)
{
if(connect) //...
}
One way to do it, is to create an init() function:
public Foo()
{
// ...
init();
}
protected Foo(bool connect)
{
// ...
if (connect) {
init();
}
}
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