Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast/Easy way to run a method based on a condition

Tags:

operators

c#

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();
like image 312
rtuner Avatar asked Sep 17 '12 13:09

rtuner


People also ask

How many conditions can you have in an if statement?

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.

How do you add multiple conditions to an if statement in Java?

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.

What are the different types of conditional statements in Java?

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.


2 Answers

It is possible, but it is not readable. The if statement is much better.

(Extender.GetSettings<string>("User") == null ? (Action)ConfigureApp : loadUser)();
like image 51
Sergey Kalinichenko Avatar answered Sep 29 '22 18:09

Sergey Kalinichenko


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.

like image 27
smartcaveman Avatar answered Sep 29 '22 16:09

smartcaveman