I have a class with different constructors. One constructor, nothing is passed through (creating a new record), the other an ID is passed through (which is used for an update). I’d like to test for a condition and make a new instance of the class object based on the outcome. My problem is that the object doesn’t carry out of the if statement.
protected void Position()
{
if (Session["PositionID"] == null)
{
JobPosition p = new JobPosition();
}
else
{
JobPosition p = new JobPosition(Convert.ToInt32(Session["PositionID"]));
}
p.positionTitle= pTitle.text;
p.positionMission= pMission.text;
p.positionDepartment= pDept.text;
Session["PositionID"] = Convert.ToString(p.SaveDB());
}
p cannot be used in the current context. I could copy my code into each condition, it just seems like I shouldn’t need to do that.
How can I use p?
You need to move the declaration of
pto above the if statement:If you declare a variable inside a local scope, it is not accessible when you leave that scope.