Search code examples
c#scopefieldvariable-assignment

Setting string variable after an if statement


After I set a string variable in an if() statement, the variable does not exist.

if (wallThicknessCBO.SelectedItem.ToString() == "2x6")
{
    if (wallH <= 8)
    {
        MessageBox.Show("2x6 and 8");
        string w_Prod_Code = "2608STUD";
        MessageBox.Show(w_Prod_Code);//messagebox shows w_Prod_Code
    }

}

//MessageBox.Show(w_Prod_Code); //says w_Prod_code does not exist

I attempted this at the beginning of the method, but the 2nd message box just shows up as blank.

string w_Prod_Code = "";
public void WallThickness()

What would I need to do to use the string variable from the if statement?


Solution

  • Change

    string w_Prod_Code = "2608STUD";
    

    to only

    w_Prod_Code = "2608STUD";
    

    or better yet

    this.w_Prod_Code = "2608STUD";
    

    Right now the question's code defines two different things named w_Prod_Code:

    • A field w_Prod_Code whose value never changes from "" and
    • A variable defined inside a nested loop, that isn't visible outside the block it was declared in. The variable hides the field in its scope

    There's probably an Intellisense or Resharper message warning that the variable is hiding the field.

    It's a very good idea to use different naming for variables and fields. If you intend to use the same names, make sure you use this. to refer to fields, eg this.prod_code.