Local variable with same name as instance variable = unexpected results

c#, instance-variables, local-variables

Solution

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.

You are not seeing the instance variable, you see the local variable. The instance variable is never set, because the locally scoped variable is hiding the instance variable during it's scope lifetime.

From the spec:

3.7.1 Name hiding

The scope of an entity typically encompasses more program text than the declaration space of the entity. In particular, the scope of an entity may include declarations that introduce new declaration spaces containing entities of the same name. Such declarations cause the original entity to become hidden. Conversely, an entity is said to be visible when it is not hidden.

Name hiding occurs when scopes overlap through nesting and when scopes overlap through inheritance. The characteristics of the two types of hiding are described in the following sections.

Name hiding through nesting can occur as a result of nesting namespaces or types within namespaces, as a result of nesting types within classes or structs, and as a result of parameter and local variable declarations

Problem

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?

Original source