Reputation: 80
I have this long loop of if..else. Can anybody help me in knowing if "switch case" is better for this or "if..else"?
if (meals == null)
{
bfast.Hide();
lunch_rb.Hide();
dinner_rb.Hide();
}
else if (meals != null)
{
if (breakfast != null && lunch == null && dinner == null)
{
lunch_rb.Hide();
dinner_rb.Hide();
}
if (breakfast == null && lunch != null && dinner == null)
{
bfast.Hide();
dinner_rb.Hide();
}
if (breakfast == null && lunch == null && dinner != null)
{
bfast.Hide();
lunch_rb.Hide();
}
if (breakfast != null && lunch != null && dinner == null)
{
dinner_rb.Hide();
}
if (breakfast != null && lunch == null && dinner != null)
{
lunch_rb.Hide();
}
if (lunch != null && breakfast == null && dinner != null)
{
bfast.Hide();
}
I am developing an application for windows CE 5.0 (if this helps)
Upvotes: 0
Views: 242
Reputation: 1058
The performance level between if
and switch
statements is not much difference. Anyway your code is a mess of conditions. Take into consideration the answer of Pigueiras. Something like
bfast.Hide();
lunch_rb.Hide();
dinner_rb.Hide();
if (meals != null) {
if (breakfast != null)
bfast.Show();
if (lunch =! null)
lunch_rb.Show();
if (dinner =! null)
dinner_rb.Show();
}
Upvotes: 0
Reputation: 43
Switch case is always better than if...else if because it needs less typing and your codes will be easier to read and understand.I myself just use "else if" when I forget switch's style in exam's!!!
Upvotes: 0
Reputation: 148150
You can try something like this, As you have condition on multiple variables you will need to make expression for passing it to switch so using if as given below might make it simple.
if (breakfast == null)
bfast.Hide();
if (lunch == null)
lunch_rb.Hide();
if (dinner == null)
dinner_rb.Hide();
Upvotes: 6
Reputation: 19356
I think the better solution in this case is:
if (breakfast == null)
bfast.Hide();
if (lunch == null)
lunch_rb.Hide();
if (dinner == null)
dinner_rb.Hide();
Upvotes: 10
Reputation: 1369
For this question, I think if...else
is good enough. switch...case
cannot deal with such a complicated situation. Feel free to use it.
Upvotes: 0
Reputation: 6326
For this particular scenario if-else is better because you have complex conditions and that's something switch-case can't do I believe.
Upvotes: 1