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#
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.
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.
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