Alternative for if-else

Below is my code:

int a = 4;
if (a > 3)
{
    Label1.Text = "Hello";
}
else
{
    Label1.Text = "Hi!";
}
//Alternate for if-else
Label1.Text = (a > 3) ? "Hello" : "Hi!";

As we know, both if-else and alternate for if-else produce the same result. I was wondering if I would have more than one statement. For instance

int a = 4;
if (a > 3)
{
    Label1.Text = "Hello";
    Label2.Text = "How are you?";
}
else
{
    Label1.Text = "Hi";
    Label2.Text = "How do you do"";
}

So, is there an alternative for this? I'm sure there is something that C # offers that I can use. Thanks at Advance.

PS I'm new to C #

+4
source share
8 answers

This is probably the best solution. It is very easy to read and see exactly what you are doing. Using a ternary operator even for one operator can sometimes read a bit depending on your code.

. , if, , , .

+8

, , .

, - . if, , :

int a = 4;
if (a > 3)
{
    SetLabelToHello();
}
else
{
    SetLabelToHi();
}

// ....

public void SetLabelToHello()
{
    Label1.Text = "Hello";
    Label2.Text = "How are you?";
}

public void SetLabelToHi()
{
    Label1.Text = "Hi";
    Label2.Text = "How do you do";
}

if, , .

+3

public int SetLabels(string label1text, string label2text)
{
   try
   {
        Label1.Text = label1text;
        Label2.Text = label2text;

        return 0;
   }
   catch
   {
        return 1;
   }
}


var result = a > 3 ? SetLabels("Hello", "How are you?") : SetLabels("Hi!", "How do you do");
+3

# - , . , , # .

. .

+2
, .

:

Label1.Text = a > 3 ? "Hello" : "Hi";
Label2.Text = a > 3 ? "How are you?" : "How do you do?";

DRY,

bool veryDryCondition = a > 3;
Label1.Text = veryDryCondition ? "Hello" : "Hi";
Label2.Text = veryDryCondition ? "How are you?" : "How do you do?";

if - .

?: , , (, ) . , - if .

+2

Q: ", ?"

A: , . , ... .

, . , ?

Action action;
int a = 4;

if (a > 3)
{
    action = new Action(() => {
        Label1.Text = "Hello";
        Label2.Text = "How are you?";
    });

}
else
{
    action = new Action(() => {
        Label1.Text = "Hi";
        Label2.Text = "How do you do"";
    });
}

action();
+2

- , / . .

, ? .

int a = 4;
var aIsGreaterThanThree = (a > 3)
if (aIsGreaterThanThree)
{
   SetLabelsToHello();
}
else 
{
   SetLabelsToHi();
}

void SetLablesToHello()
{  
   Label1.Text = "Hello";
   Label2.Text = "How are you?";
}

void SetLabelsToHi() 
{
   Label1.Text = "Hi";
   Label2.Text = "How do you do";
}

if {} if.

+2

? , :

Label1.Text = a > 3 ? "Hello" : "Hi!";
Label2.Text = a > 3 ? "How are you?" : "How do you do";

, , , . if-else, .

+1

Source: https://habr.com/ru/post/1543361/


All Articles