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");
}
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.
No.
The ternary operator (?:) must be, as a whole, an expression -- that is, something that can be assigned to something.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With