ASP.NET 4.0 Webforms project. I have the following in my code-behind.
public partial class _Default : System.Web.UI.Page
{
private string testVar;
protected override void OnInit(EventArgs e)
{
string testVar = "test";
}
protected void Page_Load(object sender, EventArgs e)
{
var whatsTheValue = testVar;
}
}
I'm setting a break point inside each method. When the local variable, testVar
, is set in OnInit
, if I quick watch the instance variable, it also has the value "test". When I play through to Page_Load
, the instance variable's value is null
.
I ran across this by accident but the behavior is confusing to me. I'm actually surprised that it compiles. I would have expected to see some sort of warning about having two variables with the same name. That being said, it's even more confusing to me that the instance variable picks up the assignment in OnInit, but then immediately loses it when that method is exited.
Can someone explain this behavior to me?
See Question&Answers more detail:os