Search code examples
c#operatorsshorthandshorthand-if

if (true) Shorthand


Is there a shorthand when checking a boolean for true?
Example:

if (autoConnect) Connect();

We can do

return IsOpen() ? true : false;

But I cant get

autoConnect ? Connect();  

running. Is there a way to do this?


Solution

  • You could write an extension method:

    public static void _(this bool b, Action ifTrue)
    {
        if (b) { ifTrue(); }
    }
    

    then you could write:

    autoConnect._(Connect);
    

    although obviously this is not very readable and is not recommended.