Search code examples
c#variable-assignmentconditional-operator

Ternary conditional operator for the left-hand operand in C#


Is it possible to choose the destination variable based on some inline condition without the if statement?

(!RTL ? padLeft : padRight) = NearBorder.LineWidth;

Solution

  • If you are using a new enough version of C# (7.2+), and those variables are locals or fields then you can use ref locals;

    (!RTL ? ref padLeft : ref padRight) = NearBorder.LineWidth;
    

    See this sharplab link for an example. Note that the proposal docs (which refer to this as conditional ref) indicate that this is still a proposal. The Championed GitHub issue is still open but seems to indicate the only thing missing is a true specification. This comment on that issue suggests it was all implemented as part of the greater ref readonly theme.

    All aside, this code works for me in both SharpLab and locally in VS2019 (latest, non-preview, using dotnet core 3.0)

    If those variables were fields, you could also use a ref return and encapsulate the logic into a function. For example:

    // class fields
    int padLeft, padRight;  
    // ref returning method 
    private ref int GetPad() => ref (!RTL ? ref padLeft : ref padRight);
    // actually use it
    void SetPad() {
        // assignment to a method! 
        GetPad() = NearBorder.LineWidth;
    } 
    

    For more information about the concept of ref locals and ref returns (originally part of C# 7), see this MSDN article.