Is there a way to run a method based on a conditional statement like a null-coalescing/ternary operator?
Sometimes, I have something like this in my code:
if(Extender.GetSetting<string>("User") == null)
{
ConfigureApp();
}
else
{
loadUser();
}
Is there a way I can have something like:
Extender.GetSettings<string>("User")?? ConfigureApp() : loadUser();
OR
Extender.GetSettings<string>("User") == null ? ConfigureApp() : loadUser();
Simple syntax Please note that the IFS function allows you to test up to 127 different conditions. However, we don't recommend nesting too many conditions with IF or IFS statements. This is because multiple conditions need to be entered in the correct order, and can be very difficult to build, test and update.
We can either use one condition or multiple conditions, but the result should always be a boolean. When using multiple conditions, we use the logical AND && and logical OR || operators. Note: Logical AND && returns true if both statements are true. Logical OR || returns true if any one of the statements is true.
In Java, there are two forms of conditional statements: • the if-else statement, to choose between two alternatives; • the switch statement, to choose between multiple alternatives.
It is possible, but it is not readable. The if
statement is much better.
(Extender.GetSettings<string>("User") == null ? (Action)ConfigureApp : loadUser)();
You can write a line like:
(Extender.GetSetting<string>("User") == null ? (Action)(()=>ConfigureApp()) : (Action)(()=>loadUser()) )();
However, the only difference this code adds to your if
statement is slower performance due to the construction of the delegates. It is not a good idea.
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