unreachable code detected - c#

I am getting unreachable code detected for the second if statement. Can you please let me know what went wrong?
private bool ValidateSettings()
{
if (chkDownload.Checked && String.IsNullOrEmpty(txtAppName.Text))
{
divAppDownloadError.Visible=true;
return false;
}
else
{
return true;
}
if (chkpplaORfmp.Checked && String.IsNullOrEmpty(txtfmpORppla.Text))
{
divXPAAPPDownloadError.Visible = true;
return false;
}
else
{
return true;
}
}

This is because the first if/else block will return either way - no code after that block will execute:
if(chkDownload.Checked && String.IsNullOrEmpty(txtAppName.Text))
{
// You either return here
divAppDownloadError.Visible=true;
return false;
}
else
{
// or here - after this statement how can anything
// else possible execute?
return true;
}

Perhaps you want to remove the else blocks and just return true at the end.
Looks like you want to return false if any of the settings are not as expected. Let:
condition1 = chkDownload.Checked && String.IsNullOrEmpty(txtAppName.Text)
condition2 = chkpplaORfmp.Checked && String.IsNullOrEmpty(txtfmpORppla.Text)
The way it is written, we have
(condition1, condition2) = (true, true) => return true
(condition1, condition2) = (true, false) => return true
(condition1, condition2) = (false, true) => return false
(condition1, condition2) = (false, false) => return false
What it looks like you want is:
(condition1, condition2) = (true, true) => return true
(condition1, condition2) = (true, false) => return false
(condition1, condition2) = (false, true) => return false
(condition1, condition2) = (false, false) => return false

Your code is the equivalent of this, since both the if and else contain return statements:
private bool ValidateSettings()
{
if(chkDownload.Checked && String.IsNullOrEmpty(txtAppName.Text))
{
divAppDownloadError.Visible=true;
return false;
}
return true;
}

Samuel Carrijo is right; I think what you mean to do is check if any invalidating conditions are held and, if so, return false. But to check them all you must not return true until the end:
private bool ValidateSettings()
{
if (chkDownload.Checked && String.IsNullOrEmpty(txtAppName.Text))
{
divAppDownloadError.Visible=true;
return false;
}
if (chkpplaORfmp.Checked && String.IsNullOrEmpty(txtfmpORppla.Text))
{
divXPAAPPDownloadError.Visible = true;
return false;
}
// if you've gotten this far, neither of the
// invalidating conditions above were held;
// so you're good!
return true;
}

private bool ValidateSettings()
{
if ((chkDownload.Checked && String.IsNullOrEmpty(txtAppName.Text))||
(chkpplaORfmp.Checked && String.IsNullOrEmpty(txtfmpORppla.Text)))
{
if (chkDownload.Checked)
divAppDownloadError.Visible=true;
else divXPAAPPDownloadError.Visible = true;
return false;
}
return true;
}
Code simplified

private bool ValidateSettings()
{
if (chkDownload.Checked && String.IsNullOrEmpty(txtAppName.Text) && chkpplaORfmp.Checked && String.IsNullOrEmpty(txtfmpORppla.Text))
{
divAppDownloadError.Visible = true;
divXPAAPPDownloadError.Visible = true;
return false;
}
if ((chkDownload.Checked && String.IsNullOrEmpty(txtAppName.Text)) || (chkpplaORfmp.Checked && String.IsNullOrEmpty(txtfmpORppla.Text)))
{
if (chkDownload.Checked && String.IsNullOrEmpty(txtAppName.Text))
{
divAppDownloadError.Visible = true;
divXPAAPPDownloadError.Visible = false;
}
else
{
divXPAAPPDownloadError.Visible = true;
divAppDownloadError.Visible = false;
}
return false;
} return true;
}
this is working

Related

Is there any possibility to simplify the nested condition into non nested in C#?

I have 3 conditions to check before returning true or false.
Here is the table:
This can be achieved using below logic
if(!COND1 && !COND2)
{
if(COND3)
{
return False
}
else
{
return True
}
}
else
{
return true
}
Can this be simplified without using nested if ?
you can write it:
if (a && b && !c)
{
return false;
}
return true;
or simply:
return !(a && b && !c)

TreeListView and hierarchical checkboxes

I am using TreeListView with:
this.tlv.CheckBoxes = true;
this.tlv.TriStateCheckBoxes = true;
this.tlv.HierarchicalCheckboxes = true;
Hierarchical with tristate works well, except one: the user can set the CheckState.Indeterminate by clicking the mouse, and I don't need it. For this I use 2 delegate that are not working correctly. How to make that work?
this.tvl.CheckStateGetter = delegate(object rowObject)
{
if (((ModelData)rowObject).IsChecked == true)
{
return CheckState.Checked;
}
else
{
if (((ModelData)rowObject).IsChecked == false)
{
return CheckState.Unchecked;
}
else
{
return CheckState.Indeterminate;
}
}
};
this.tvl.CheckStatePutter = delegate(object rowObject, CheckState newValue)
{
if (((ModelData)rowObject).Child.Count > 0)
{
if ((((ModelData)rowObject).Child.Where(x => x.IsChecked != null).Any(x => (bool)x.IsChecked) &&
((ModelData)rowObject).Child.Where(x => x.IsChecked != null).Any(x => !(bool)x.IsChecked)) ||
(((ModelData)rowObject).Child.Any(x => x.IsChecked == null)))
{
((ModelData)rowObject).IsChecked = null;
return CheckState.Indeterminate;
}
else
{
if (((ModelData)rowObject).Child.Where(x => x.IsChecked != null).All(x => (bool)x.IsChecked))
{
((ModelData)rowObject).IsChecked = true;
return CheckState.Checked;
}
else
{
((ModelData)rowObject).IsChecked = false;
return CheckState.Unchecked;
}
}
}
else
{
((ModelData)rowObject).IsChecked = (newValue == CheckState.Checked) ? true : false;
return newValue;
}
};
According to the documentation, "CheckStateGetters" are not allowed in the treelistview.
From the webpage:
One major problem is that we don’t know the checkedness of all the
subitems. When an ObjectListView has a CheckStateGetter installed, the
only way we can know if an item is checked is by calling the
CheckStateGetter on that item. We can’t reason about what is checked
or unchecked – we always have to ask. In our disk browser example, we
would have to ask all 700,000 items if it was checked. That’s never
going to work, so with hierarchical checkboxes, we don’t allow
CheckStateGetters to be installed.
http://objectlistview.sourceforge.net/cs/blog7.html

Why does my function tell me there's an unreachable code detected? c#

I created this function:
public bool checkFunds(int x)
{
if(checksBox.CheckState == CheckState.Checked && OriginalMain.temporaryChecks >= x)
{
return true;
}
else
{
MessageBox.Show("Error! Insufficient funds");
return false;
}
if(savingsBox.CheckState == CheckState.Checked && OriginalMain.temporarySavings >= x)
{
return true;
}
else
{
MessageBox.Show("Error! Insufficient funds!");
return false;
}
}
This code is for a windows form application. I'm making a bank simulator where you can choose from two different accounts to take your money out. This function in particular checks which checkbox you picked and checks if there are enough funds available on the chosen account. However C# keeps telling me that the second if is an unreachable code. Why is that? How can I fix it?
You get a warning, because your function will necessarily exit at one of these places:
if(checksBox.CheckState == CheckState.Checked && OriginalMain.temporaryChecks >= x)
{
return true; // <-- if the condition is true, your function will exit here
}
else
{
MessageBox.Show("Error! Insufficient funds");
return false; // <-- if the condition is false, your function will exit here
}
// this means this place in code is NEVER reached, so you get the warning
if(savingsBox.CheckState == CheckState.Checked && OriginalMain.temporarySavings >= x)
Most likely you need logic similar to this:
if(checksBox.CheckState == CheckState.Checked)
{
if(OriginalMain.temporaryChecks >= x)
{
return true;
}
else
{
MessageBox.Show("Error! Insufficient funds");
return false;
}
}
if(savingsBox.CheckState == CheckState.Checked)
{
if(OriginalMain.temporarySavings >= x)
{
return true;
}
else
{
MessageBox.Show("Error! Insufficient funds!");
return false;
}
}

Simplifying IF statement logic - inner logic overlap

Can the below logical if conditions be simplified ?
I have wrote this code but some parts are overlapping so I thought to seek for some help to see whether it can be simplified...
I have actually three different fields but following the same patterns.
EDIT :
if (Row.ReceivableAmount_IsNull == true && Row.CustomerID == LastCustomerID)
{
if (LastReceivableAmount == null)
{
Row.PreviousReceivableAmount_IsNull = true;
}
else
{
Row.PreviousReceivableAmount = LastReceivableAmount.GetValueOrDefault();
}
}
else
{
Row.PreviousReceivableAmount = LastReceivableAmount.GetValueOrDefault();
LastReceivableAmount = Row.ReceivableAmount;
}
if (Row.SaleAmount_IsNull == true && Row.CustomerID == LastCustomerID)
{
if (LastSaleDate == null)
{
Row.PreviousSaleDate_IsNull = true;
}
else
{
Row.PreviousSaleDate = LastSaleDate.GetValueOrDefault();
}
}
else
{
if (LastSaleDate == null)
{
Row.PreviousSaleDate_IsNull = true;
}
else
{
Row.PreviousSaleDate = LastSaleDate.GetValueOrDefault();
}
LastSaleDate = Row.Date;
}
if (Row.PaymentAmount_IsNull == true && Row.CustomerID == LastCustomerID)
{
if (LastPaymentDate == null)
{
Row.PreviousPaymentDate_IsNull = true;
}
else
{
Row.PreviousPaymentDate = LastPaymentDate.GetValueOrDefault();
}
}
else
{
Row.PreviousPaymentDate = LastPaymentDate.GetValueOrDefault();
LastPaymentDate = Row.Date;
}
Yes, you only care about LastSaleDate in your outer if condition, so move everything else out.
Once you've moved it out, you can invert your original condition, reducing your if/else to just an if.
if (LastReceivableAmount == null)
{
Row.PreviousReceivableAmount_IsNull = true;
}
else
{
Row.PreviousReceivableAmount = LastReceivableAmount.GetValueOrDefault();
}
if (!Row.ReceivableAmount_IsNull || Row.CustomerID != LastCustomerID)
{
Row.PreviousReceivableAmount = LastReceivableAmount.GetValueOrDefault();
LastReceivableAmount = Row.ReceivableAmount;
}
if (LastSaleDate == null)
{
Row.PreviousSaleDate_IsNull = true;
}
else
{
Row.PreviousSaleDate = LastSaleDate.GetValueOrDefault();
}
if (!Row.SaleAmount_IsNull || Row.CustomerID != LastCustomerID)
{
LastSaleDate = Row.Date;
}
if (LastPaymentDate == null)
{
Row.PreviousPaymentDate_IsNull = true;
}
else
{
Row.PreviousPaymentDate = LastPaymentDate.GetValueOrDefault();
}
if (!Row.PaymentAmount_IsNull == true || Row.CustomerID != LastCustomerID)
{
Row.PreviousPaymentDate = LastPaymentDate.GetValueOrDefault();
LastPaymentDate = Row.Date;
}
Since both branches of the if are similar, except one statement, you could use the following approach:
if (LastSaleDate == null)
{
Row.PreviousSaleDate_IsNull = true;
}
else
{
Row.PreviousSaleDate = LastSaleDate.GetValueOrDefault();
}
if (!Row.SaleAmount_IsNull || Row.CustomerID != LastCustomerID)
{
LastSaleDate = Row.Date;
}

Boolean Function c# not all code return a value

What am I doing wrong here?
At the end of the function, I'm returning the result.
public bool isStipends()
{
try
{
bool result = true;
if (tbstipend.Text == "" || tbstipend.Text == "Required")
{
tbstipend.Text = "Required";
tbstipend.BackColor = Color.Red;
tbstipend.ForeColor = Color.White;
result = false;
}
else if (tbstipendperperiod.Text == "" || tbstipendperperiod.Text == "Required")
{
tbstipendperperiod.Text = "Required";
tbstipendperperiod.BackColor = Color.Red;
tbstipendperperiod.ForeColor = Color.White;
result = false;
}
else if (tbstipendsperinterval.Text == "" || tbstipendsperinterval.Text == "Required")
{
tbstipendsperinterval.Text = "Required";
tbstipendsperinterval.BackColor = Color.Red;
tbstipendsperinterval.ForeColor = Color.White;
result = false;
}
else if (tbstipendrate.Text == "" || tbstipendrate.Text == "Required")
{
tbstipendrate.Text = "Required";
tbstipendrate.BackColor = Color.Red;
tbstipendrate.ForeColor = Color.White;
result = false;
}
else
{
return result;
}
}
catch
{
return false;
}
}
In the code behind of the button, I call:
private void btnupdatestipends_Click(object sender, EventArgs e)
{
try
{
if (isStipends() == true)
{
MessageBox.Show("TEST");
}
}
catch { }
}
However, it gives me an error on the function itself.
Error 3 'AddressBookMaint.Form1.isStipends()': not all code paths return a value C:\Win\AddressBookMaint\AddressBookMaint\Form1.cs 5040 22 AddressBookMaint
Any suggestions?
Thank you.
Error 1
You are only returning if none of the if's are true since the `return` is in the last `else` clause.
Solution
Break out the `return` from the last `else` and place it in the `try` block *(or even outside of the try/catch and you will solve error 2 as well)*.
Error 2
You will only return if there are no exceptions since you have the `return` at the end of the `try` block and no `return` in the `catch` block.
Solution
Add a `return` in the `catch` block and the code will compile.
Here's a working version of your code
public bool isStipends()
{
bool result = true;
try
{
if (tbstipend.Text == "" || tbstipend.Text == "Required")
{
tbstipend.Text = "Required";
tbstipend.BackColor = Color.Red;
tbstipend.ForeColor = Color.White;
result = false;
}
else if (tbstipendperperiod.Text == "" || tbstipendperperiod.Text == "Required")
{
tbstipendperperiod.Text = "Required";
tbstipendperperiod.BackColor = Color.Red;
tbstipendperperiod.ForeColor = Color.White;
result = false;
}
else if (tbstipendsperinterval.Text == "" || tbstipendsperinterval.Text == "Required")
{
tbstipendsperinterval.Text = "Required";
tbstipendsperinterval.BackColor = Color.Red;
tbstipendsperinterval.ForeColor = Color.White;
result = false;
}
else if (tbstipendrate.Text == "" || tbstipendrate.Text == "Required")
{
tbstipendrate.Text = "Required";
tbstipendrate.BackColor = Color.Red;
tbstipendrate.ForeColor = Color.White;
result = false;
}
}
catch
{
result = false;
}
return result;
}
You either need to return something in your catch:
public bool Method() {
try {
return true;
}
catch {
return false;
}
}
Or just return a single value at the bottom:
public bool Method() {
bool result = false;
try {
...
result = true;
}
catch {}
return result;
}
replace your method isStipends by this on:
public bool isStipends()
{
try
{
bool result = true;
if (tbstipend.Text == "" || tbstipend.Text == "Required")
{
tbstipend.Text = "Required";
tbstipend.BackColor = Color.Red;
tbstipend.ForeColor = Color.White;
result = false;
}
else if (tbstipendperperiod.Text == "" || tbstipendperperiod.Text == "Required")
{
tbstipendperperiod.Text = "Required";
tbstipendperperiod.BackColor = Color.Red;
tbstipendperperiod.ForeColor = Color.White;
result = false;
}
else if (tbstipendsperinterval.Text == "" || tbstipendsperinterval.Text == "Required")
{
tbstipendsperinterval.Text = "Required";
tbstipendsperinterval.BackColor = Color.Red;
tbstipendsperinterval.ForeColor = Color.White;
result = false;
}
else if (tbstipendrate.Text == "" || tbstipendrate.Text == "Required")
{
tbstipendrate.Text = "Required";
tbstipendrate.BackColor = Color.Red;
tbstipendrate.ForeColor = Color.White;
result = false;
}
return result;
}
catch { }
}
Your code only specifies the return in the final else block. In all your other code paths, including the catch block, you haven't specified any return value. You can drop that final else block and add a return value at the end of your function, like this:
public bool isStipends()
{
bool result = true;
try
{
...
}
catch
{
result = false;
}
return result;
}
However, catching all exceptions like this is very bad practice, and you certainly don't need to do it inside every function. You should only catch the exceptions you can meaningfully handle and allow the rest to bubble up. Set a global unhandled exception if need be to gracefully bail out of your application.
See Best Practices for Exceptions
The error is telling you that there are ways that do not return any value, if there is a mistake your catch instruction will returns nothing.
returns some value in your instruction catch.
You are not returning anything anywhere in your code... except for your last else statement. To compile all paths should return a bool value for your method. You should return a value in every if or if else and else statement, and in your catch block.
This will work:
public bool isStipends()
{
try
{
bool result = true;
if (tbstipend.Text == "" || tbstipend.Text == "Required")
{
tbstipend.Text = "Required";
tbstipend.BackColor = Color.Red;
tbstipend.ForeColor = Color.White;
result = false;
}
else if (tbstipendperperiod.Text == "" || tbstipendperperiod.Text == "Required")
{
tbstipendperperiod.Text = "Required";
tbstipendperperiod.BackColor = Color.Red;
tbstipendperperiod.ForeColor = Color.White;
result = false;
}
else if (tbstipendsperinterval.Text == "" || tbstipendsperinterval.Text == "Required")
{
tbstipendsperinterval.Text = "Required";
tbstipendsperinterval.BackColor = Color.Red;
tbstipendsperinterval.ForeColor = Color.White;
result = false;
}
else if (tbstipendrate.Text == "" || tbstipendrate.Text == "Required")
{
tbstipendrate.Text = "Required";
tbstipendrate.BackColor = Color.Red;
tbstipendrate.ForeColor = Color.White;
result = false;
}
else
{
return result;
}
}
catch
{
return false;
}
return result;
}

Categories

Resources