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)
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();
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();
For this particular scenario if-else is better because you have complex conditions and that's something switch-case can't do I believe.
For this question, I think if...else is good enough. switch...case cannot deal with such a complicated situation. Feel free to use it.
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!!!
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();
}
Related
When the check against the emailaddress is added to the if statement, as per below, the if statement if (origin.Equals(true)).
bool origin = false;
Contact contact = item as Contact;
foreach (Item subItem in contactItems)
{
Contact subcontact = subItem as Contact;
if ((contact.DisplayName.Equals(subcontact.DisplayName) || (contact.DisplayName is null && subcontact.DisplayName is null)) && ((contact.CompanyName is null && subcontact.CompanyName is null) || (contact.CompanyName.Equals(subcontact.CompanyName)) && ((contact.EmailAddresses[EmailAddressKey.EmailAddress1] is null && subcontact.EmailAddresses[EmailAddressKey.EmailAddress1] is null) || (contact.EmailAddresses[EmailAddressKey.EmailAddress1].Equals(subcontact.EmailAddresses[EmailAddressKey.EmailAddress1])))))
{
if (origin.Equals(true))
{
try
{
Console.WriteLine(contact.DisplayName + " " + subcontact.DisplayName);
Console.WriteLine(contact.EmailAddresses[EmailAddressKey.EmailAddress1]);
subcontact.Delete(DeleteMode.HardDelete);
}
catch
{
Console.WriteLine("Cannot delete" + " " + subcontact.DisplayName);
}
}
origin = true;
}
}
If I remove the if (origin.Equals(true)) or removed && ((contact.EmailAddresses[EmailAddressKey.EmailAddress1] is null && subcontact.EmailAddresses[EmailAddressKey.EmailAddress1] is null) || (contact.EmailAddresses[EmailAddressKey.EmailAddress1].Equals(subcontact.EmailAddresses[EmailAddressKey.EmailAddress1])) from the other if statement, the contact goes through the try-catch block.
Can anyone see why?
if ((contact.DisplayName.Equals(subcontact.DisplayName) || (contact.DisplayName is null && subcontact.DisplayName is null)) && ((contact.CompanyName is null && subcontact.CompanyName is null) || (contact.CompanyName.Equals(subcontact.CompanyName)) && ((contact.EmailAddresses[EmailAddressKey.EmailAddress1] is null && subcontact.EmailAddresses[EmailAddressKey.EmailAddress1] is null) || (contact.EmailAddresses[EmailAddressKey.EmailAddress1].Equals(subcontact.EmailAddresses[EmailAddressKey.EmailAddress1])))))
should be:
if ((contact.DisplayName.Equals(subcontact.DisplayName) || (contact.DisplayName is null && subcontact.DisplayName is null)
&& ((contact.CompanyName is null && subcontact.CompanyName is null) || (contact.CompanyName.Equals(subcontact.CompanyName))
&& ((contact.EmailAddresses[EmailAddressKey.EmailAddress1] is null && subcontact.EmailAddresses[EmailAddressKey.EmailAddress1] is null) || (contact.EmailAddresses[EmailAddressKey.EmailAddress1].Equals(subcontact.EmailAddresses[EmailAddressKey.EmailAddress1])))
the problem as I can see, is in the amount of ( ) you use, which I believe is incorrect.
Try to clean up your if statements to prevent these types of mistakes from happening, since this one was pretty long, and a few of your parenthesis are unnecessary
EDIT:
I tried running some code and it works. I did make some mistakes in the sample of the IF statement I mentioned above.. Maybe try copying my code, and substituting your specific code into it. It should work this way.
public static void Main()
{
bool origin = false;
int[] t = {0,4,6,8,5,6,4,5};
foreach(int i in t){
if ((true || (true && true)) // if ((contact.DisplayName.Equals(subcontact.DisplayName) || (contact.DisplayName is null && subcontact.DisplayName is null))
&& ((true && true) || (true)) // && ((contact.CompanyName is null && subcontact.CompanyName is null) || (contact.CompanyName.Equals(subcontact.CompanyName)))
&& ((true && true) || (true))) // && ((contact.EmailAddresses[EmailAddressKey.EmailAddress1] is null && subcontact.EmailAddresses[EmailAddressKey.EmailAddress1] is null) || (contact.EmailAddresses[EmailAddressKey.EmailAddress1].Equals(subcontact.EmailAddresses[EmailAddressKey.EmailAddress1])))))
{
if (origin.Equals(true))
{
try
{
Console.WriteLine("here");
}
catch
{
Console.WriteLine("Cannot delete" );
}
}
origin = true;
}
}
}
I suggest a little Helper:
private bool EqualOrBothNull( string fromContact, string fromSubcontact )
{
if ( fromContact == null && fromSubcontact == null ) return true;
if ( fromContact != null && fromContact.Equals(fromSubcontact) ) return true;
return false;
}
then you can use it like this:
if ( EqualOrBothNull( contact.DisplayName, subContact.DisplayName ) &&
EqualOrBothNull( contact.CompanyName, subContact.CompanyName ) &&
EqualOrBothNull( contact.EmailAddresses[EmailAddressKey.EmailAddress1],
subContact.EmailAddresses[EmailAddressKey.EmailAddress1])
)
{
// ...
}
This increases readability and will make it easier to find the bug if any.
Thanks for all the potential answers unfortunately they didn't fix the issue, the code is much easier to read though! In the end I separated the email address check to another IF statement which seems to be working
I have a object with type:
dynamic {System.DBNull}
I want to check it:
if (myObject!= null || myObject!= DBNull.Value)
{
MessageBox.Show("Oh hi");
}
But the MessageBox always appears. Whats wrong, is it another type?
This expression is always true
myObject != null || myObject != DBNull.Value
because myObject cannot be null and DBNull.Value at the same time. Replace || with && to fix.
Try this code
if(myObject != DBNull.Value)
{
MessageBox.Show("Oh hi");
}
or
if(myObject != null && myObject != DBNull.Value)
{
MessageBox.Show("Oh hi");
}
There is also a function for checking for DBNull:
if(myObject != null && !Convert.IsDBNull(myObject))
{
MessageBox.Show("Oh hi");
}
I have an IF statement that is supposed to make sure the TextBox1.Text and TextBox2.Text do not match or are not blank. If they don't match or are not blank then it is supposed to assign the text in the boxes to two string variable. What I can't figure out is why when I leave the two textboxes blank the true statement still fires.
if ((tbStartBreak2.Text != tbEndBreak2.Text) || (tbStartBreak2.Text == "" && tbEndBreak2.Text == ""))
{
sb2 = tbStartBreak2.Text;
se2 = tbStartBreak2.Text;
}
There are two conditions in your if statement:
if ((tbStartBreak2.Text != tbEndBreak2.Text) || (tbStartBreak2.Text == "" && tbEndBreak2.Text == ""))
The first one checks to make sure they don't match (so, good). The second checks to make sure that they are blank (so, bad). You want this:
if ((tbStartBreak2.Text != tbEndBreak2.Text) || (tbStartBreak2.Text != "" && tbEndBreak2.Text != ""))
Also, what are you trying to do? The second condition is the only one you need if you really want them not to match OR not be blank - because the only time this will be false is if they are both blank.
You wrote "OR textbox are blank", you need "OR textbox are not blank"
if ((tbStartBreak2.Text != tbEndBreak2.Text) || (tbStartBreak2.Text != "" && tbEndBreak2.Text != ""))
{
sb2 = tbStartBreak2.Text;
se2 = tbStartBreak2.Text;
}
As a side note, I'd replace "" with string.Empty for readability.
if ((tbStartBreak2.Text != tbEndBreak2.Text) || (tbStartBreak2.Text != string.Empty && tbEndBreak2.Text != string.Empty))
{
sb2 = tbStartBreak2.Text;
se2 = tbStartBreak2.Text;
}
And for even more readability, you can extract these big conditions
if (TextboxesDoNotMatch() || TextboxesAreNotEmpty())
{
sb2 = tbStartBreak2.Text;
se2 = tbStartBreak2.Text;
}
private bool TextboxesDoNotMatch()
{
return tbStartBreak2.Text != tbEndBreak2.Text;
}
private bool TextboxesAreNotEmpty()
{
return tbStartBreak2.Text != string.Empty && tbEndBreak2.Text != string.Empty;
}
If you want it to return that they are NOT blank then you need to do this
(tbStartBreak2.Text != "" && tbEndBreak2.Text != "")
you have an OR between both conditions so when both are empty the second part will be true regardless the first part
(tbStartBreak2.Text == "" && tbEndBreak2.Text == "")
this.value1 and c.value1 can both be either null or non-null. So a total of 4 combinations to test. value2 can also be null or non-null.
Can the if-then-else's below be replaced by something shorter like use the ternary operator ( if then else using the ? : operators) - and would that be a bad practice for this specific case because we are testing 4 combinations for value1 and value2?
public override bool Equals(object obj)
{
bool value1_check = false;
bool value2_check = false;
var c = obj as ObjectType;
if (this.value1 != null)
value1_check = this.value1.Equals(c.value1);
else if ((this.value1 == null) && (c.value1 == null))
value1_check = true;
else if ((this.value1 == null) && (c.value1 != null))
value1_check = c.value1.Equals(this.value1);
if (this.value2 != null)
value2_check = this.value2.Equals(c.value2);
else if ((this.value2 == null) && (c.value2 == null))
value2_check = true;
else if ((this.value2 == null) && (c.value2 != null))
value2_check = c.value2.Equals(this.value2);
return (value1_check && value2_check);
}
You can call Object.Equals(), which already does all that.
return Equals(this.Value1, c.Value1)
&& Equals(this.Value2, c.Value2);
Actually, you might want the ?? Operator.
var lhs= this.value1 ?? c.value1 ?? null;
var rhs = c.value1 ?? this.value1 ?? null;
var value1Check = lhs == rhs
Should do the same thing as yours, but almost 100% less readable!
If your still wondering about the ternary option.
value1_check= this.value1!=null? this.value1.Equals(c.value1):(c.value1!=null?c.value.Equals(this.value):value1_check=true);
I am still in the process of learning Asp.Net. I have a question . I was using an if condition in which i was checking dataset values. It is throwing me an exception whenever it is checking the condition as the dataset has not got any value. How to overcome this.
Code for this is here:
DataSet ds = merchant.getIsactiveIsconfirmedforcancelaccount(merchantID);
if (_merchant.PackageID == (int)CommonHelper.Package.Free && _merchant.AccountStatus.Contains("Awaiting"))
{
spnMerchantActiveStatus.InnerHtml = ApplicationData.MSG_AWAITING_CONFIRMATION;
}
***else if ((ds.Tables[0].Rows[0]["IsConfirmed"]).ToString() == "True" && (ds.Tables[0].Rows[0]["Active"]).ToString() == "N")***
{
_merchant.AccountStatus = "Cancelled";
spnMerchantActiveStatus.InnerHtml = _merchant.AccountStatus;
}
else if(_merchant.PackageID != (int)CommonHelper.Package.Free && ds1.Tables[0].Rows.Count == 0 && (ds2.Tables[0].Rows[0]["ConfirmationSrc"]).ToString() == "Admin")
{
_merchant.AccountStatus = "Free Trial";
spnMerchantActiveStatus.InnerHtml = _merchant.AccountStatus;
}
else
spnMerchantActiveStatus.InnerHtml = _merchant.AccountStatus;
}
The exception here is "There is no row at position 0."
Seems like you do not have any rows in your tables[0]. You can add condition to check is rows > 0 and then continue with other conditions in the IF.
You are assuming you have rows in your DataSet.
Instead of
if ((ds.Tables[0].Rows[0]["IsConfirmed"]).ToString() == "True" &&
(ds.Tables[0].Rows[0]["Active"]).ToString() == "N")
you should do something like
if ((ds.Tables[0].Rows.Count() > 0) &&
(ds.Tables[0].Rows[0]["IsConfirmed"]).ToString() == "True" &&
(ds.Tables[0].Rows[0]["Active"]).ToString() == "N")
But you really need to do fuller error checking than just that one condition affectin you right now.
EDIT: If it's not obvious why the above works, read up on short-circuiting of logical operators: http://msdn.microsoft.com/en-us/library/2a723cdk(VS.71).aspx
Try changing your else statement :
else if (
(ds.Tables[0].Rows[0]["IsConfirmed"]).ToString() == "True" &&
(ds.Tables[0].Rows[0]["Active"]).ToString() == "N")
{
_merchant.AccountStatus = "Cancelled"; spnMerchantActiveStatus.InnerHtml = _merchant.AccountStatus;
}
To
if ((null != ds.Tables[0]) && ((ds.Tables[0].Rows[0]["IsConfirmed"]).ToString() == "True") && ((ds.Tables[0].Rows[0]["Active"]).ToString() == "N"))
So that you check that the data set is not null before you check conditions on it.
or (as other posters say) check that you actually have rows in the dataset.
ds.Tables[0].Rows.Count() != 0