Lee White
Lee White

Reputation: 3729

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

Upvotes: 11

Views: 8596

Answers (3)

Eren Ersönmez
Eren Ersönmez

Reputation: 39085

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

Upvotes: 9

Fabio Marcolini
Fabio Marcolini

Reputation: 2385

You can't call this() conditionally so you have to use a method instead

public Foo()
{
    ConnectCode();
}
protected Foo(bool connect)
    : this()
{
    if(connect)
        ConnectCode();
}

Another way(don't know if it's good or if it is ok for your needs) is:

public Foo(bool connect=true)
{
    if(connect)
        ConnectCode();
}

This way the code that call Foo() don't need to be changed but you lose the protected accessibility

Upvotes: 2

Bart Friederichs
Bart Friederichs

Reputation: 33531

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

public Foo()
{
    // ...
    init();
}
protected Foo(bool connect)
{
    // ...
    if (connect) {
        init();
    }
}

Upvotes: 6

Related Questions