Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
     }
like image 528
adminSoftDK Avatar asked Jul 30 '14 16:07

adminSoftDK


2 Answers

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.

like image 153
ziya Avatar answered Sep 21 '22 08:09

ziya


No.

The ternary operator (?:) must be, as a whole, an expression -- that is, something that can be assigned to something.

like image 34
James Curran Avatar answered Sep 20 '22 08:09

James Curran