Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate 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 gives out same output. I was wondering, what if i 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 alternate for this? I am sure there is something C# has to offer which I can use. Thanks in Advance.

P.S. I am fairly new to C#

like image 629
Khan Avatar asked Nov 28 '22 15:11

Khan


2 Answers

That is probably the best solution. It is very easy to read and see exactly what you're doing. Using the ternary operator even for one statement can sometimes be a bit much to read depending on your code.

There are a huge number of alternatives here. You could say that many OOP design patterns are themselves just alternatives to if statements, but for a simple case like this it is unnecessary to go that far.

like image 113
Gentleduck Avatar answered Jan 02 '23 18:01

Gentleduck


The way you have already implemented this is already fine.

Perhaps something like this may help. It abstracts the implementation code away from the if, assuming that is what you would like:

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";
}

Using methods in this way allows you to easily add more statements to the if condition whilst keeping clean, easily maintainable code.

like image 36
rhughes Avatar answered Jan 02 '23 19:01

rhughes