Search code examples
c#out

If-else statement logic with function out parameter


I am working inside a loop to test if an external connection exists. If the connection does exist, then I want to operate on it, pulling back information. If it doesn't, then I want to open the connection. I assumed the logic would go:

if (IsConnected()) {
    OperateOnStream();
} else {
    Connect();
}

The problem is the defined interface is:

public Result IsConnected(out bool connected)

The return type, Result is a defined class elsewhere, and is actually instantiated inside IsConnected, with no useful information.

Currently I have

bool isConnected;
IsConnected(out isConnected);
if (isConnected) {
    OperateOnStream();
} else {
    Connect();
}

My question is: belonging to a function that is periodically run, this is rather inefficient. It creates an unnecessary variable, and is fairly inelegant. I can't alter the underlying API. Is there a better way? Thanks in advance.


Solution

  • You could do this:

    if (IsConnected(out bool connected) != null && connected)
    {
        OperateOnStream();
    }
    else
    {
        Connect();
    }
    

    But it's not hugely better, if at all.

    Or this:

    bool isConnected() => IsConnected(out bool connected) != null && connected;
    
    if (isConnected())
    {
        OperateOnStream();
    }
    else
    {
        Connect();
    }
    

    At the end of the day the original code is not "rather inefficient" anyway.