Search code examples
c#lambdashorthand-if

c# If else shorthand


In c# can I do something like this in a shorthand?

 bool validName = true;
 if (validName)
 {
     name = "Daniel";
     surname = "Smith";
 }
 else
 {
     MessageBox.Show("Invalid name");
 }

I was just wondering if something similar to this would work, but in this exact scenario, I know you can assign values if I did name = validName ? "Daniel" : "Not valid", but I was just wondering if i can do the below?

     validName ? 
     {
         name = "Daniel";
         surname = "Smith";
     } 
     : 
     {
         MessageBox.Show("Invalid name");
     }

Solution

  • Abusing lambda syntax and type inference:

    (validName
        ? (Action)
            (() =>
                {
                    name = "Daniel";
                    surname = "Smith";
                })
          : () =>
               {
                    MessageBox.Show("Invalid name");
               })();
    

    I know, not really an answer. If statement is way better: obviously this syntax is less readable and more importantly it has different runtime behaviour and could lead to unintended side effects because of potential closures created by the lambda expressions.

    Syntax is a bit cryptic too. It first creates two Action objects then ?: operator chooses between them and at last the chosen result is executed:

    var a1 = new Action(() => { /* if code block */ });
    var a2 = new Action(() => { /* else code block */ });
    
    Action resultingAction = test_variable ? a1 : a2;
    
    resultingAction();
    

    I put it together in one statement by executing the resulting action in place. To make it even briefer I cast the first lambda expression into an Action (instead of creating a new Action() explicitly) and taking advantage of type inference I left out the second cast.