Below is my code behind-file in my project, and as you can see i’m instantiating an object of a class called “SecretNumber” in the Page_Load. I recently had a problem accessing the object reference in the button function, because I forgot to put the reference out of the scope (private SecretNumber guessNr).
However, by some strange reason this code generates the following error: “Field ‘_Default.guessNr’ is never assigned to, and will always have its default value null.”
If I delete “private SecretNumber guessNr” (which is generating the error) the problem not being able to reach the object reference from the button function is there again, so obvious the reference is assigned with the object.
How come I get this error and how to solve it?
public partial class _Default : System.Web.UI.Page
{
private SecretNumber guessNr;
protected void Page_Load(object sender, EventArgs e) {
SecretNumber guessNr = new SecretNumber();
}
protected void btnCheckNr_Click(object sender, EventArgs e) {
if (!Page.IsValid){
return;
}
// The rest of the code goes here
}
}
You need to make a subtle change inside your Page_Load method
The way you have it, you are declaring a local variable of the same name. It is hiding the class-level field while inside the method.