0

I am fairly new to C#, and feel like this is probably an obvious answer, since I understand what the error means--but I cannot for the life of me see how to fix it! I am getting an "unreachable code detected" warning for my second if statement, so I realize it is not being called, I just don't understand where my error is, or how to go about fixing it. Any help would be greatly appreciated!

The snippet of code I am having the issue with is:

bool valid = true;
if (txtFirst.Text.Length < 1 || txtLast.Text.Length < 1 || txtAddress.Text.Length < 1 || txtCity.Text.Length < 1 || txtState.Text.Length < 1)
{
    return false;
}

string usZip = @"^\d{5}$|^\d{5}-\d{4}$";
Regex re = new Regex(usZip);

return re.IsMatch(txtZip.Text);

if (re.IsMatch(txtZip.Text))
    return (true);
else
    return (false);
return valid;
valid = false; 
John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • 2
    You are returning right above the second if statement unconditionally: `return re.IsMatch(txtZip.Text);`. Anything below that return won't be reached. – Sloth Armstrong May 21 '15 at 03:58
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders May 21 '15 at 04:07

2 Answers2

2

You have a return statement prior to your second if statement:

return re.IsMatch(txtZip.Text);

So the code below will never execute.

Additionally, you also have unreachable code below your second if, as that if statement will return a value in either case, so:

return value;
valid=false;

Will never execute either.

njack
  • 41
  • 4
0

if you want to check all the field should be field and then if ZIP match the pattern return TRUE else FALSE below code is sufficient..

because of your return statement before if/else is the reason of unreachable code.. because that return will always has true OR false value to return so it will never reach to the IF/ELSE condition..

I think below code is what you want.. check it out..

    if (txtFirst.Text.Length < 1 || txtLast.Text.Length < 1 || txtAddress.Text.Length < 1 || txtCity.Text.Length < 1 || txtState.Text.Length < 1)
    {
        return false;
    }

    string usZip = @"^\d{5}$|^\d{5}-\d{4}$";
    Regex re = new Regex(usZip);
    return re.IsMatch(txtZip.Text);
Deepak Sharma
  • 4,124
  • 1
  • 14
  • 31