Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally Call Constructor in C#

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.)

like image 418
Lee White Avatar asked May 27 '13 07:05

Lee White


2 Answers

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) //...
}
like image 159
Eren Ersönmez Avatar answered Sep 20 '22 13:09

Eren Ersönmez


One way to do it, is to create an init() function:

public Foo()
{
    // ...
    init();
}
protected Foo(bool connect)
{
    // ...
    if (connect) {
        init();
    }
}
like image 25
Bart Friederichs Avatar answered Sep 20 '22 13:09

Bart Friederichs