I have an application that’s instantiates an object from a class called “SecretNumber” when a get of the page is done. After that, I want to work with the object that’s instantiated instead of instantiating a new one.
Below is a piece of my code from the code behind-file, and the problem is that I can’t use the object reference inside the button function. I get an error telling that the name doesn’t exist in the current context.
How can this be solved? Thanks in advance!
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) {
SecretNumber guessNr = new SecretNumber();
}
protected void btnCheckNr_Click(object sender, EventArgs e) {
if (!Page.IsValid) {
return;
}
else {
var guessedNr = int.Parse(inputBox.Text);
var result = guessNr.MakeGuess(guessedNr); <- The name 'guessNr' does not exist in the current context
}
}
}
Move declaration of the variable out of the scope of the method, so it becomes a private field of the type
_Default.This shall work