Reputation: 865
The method named MoveToANewRoom(Room newRoom)
is supposed to set a variable to an instance, and it does this during the course of the method, but at the end the variable is set back to null for no discernible reason.
I ran the code in the debugger and saw that the variable named currentRoom
was set to room1
as intended during the execution of the method MoveToANewRoom(Room newRoom)
. However, when the method is finished executing, the variable currentRoom
is set back to null
again.
Am I missing something really basic?
Here's my code:
public partial class Form1 : Form
{
Room currentRoom;
public Form1()
{
InitializeComponent();
Room room1 = new Room("Living Room");
Room room2 = new Room("Dining Room");
Room room3 = new Room("Kitchen");
Room room4 = new Room("Front Yard");
Room room5 = new Room("Back Yard");
Room room6 = new Room("Garden");
room1.Exits = new Room[] { room2, room3 };
room2.Exits = new Room[] { room1, room4 };
room3.Exits = new Room[] { room1, room4 };
room4.Exits = new Room[] { room2, room3, room5, room6 };
room5.Exits = new Room[] { room4 };
room6.Exits = new Room[] { room4 };
MoveToANewRoom(room1);
}
public class Room
{
public string Name;
public Room[] Exits;
public Room(string name)
{
this.Name = name;
}
}
public void MoveToANewRoom(Room newRoom)
{
Room currentRoom = newRoom;
exits.Items.Clear();
for (int i = 0; i < currentRoom.Exits.Length; i++)
{
exits.Items.Add(currentRoom.Exits[i].Name);
exits.SelectedIndex = 0;
}
}
Upvotes: 2
Views: 92
Reputation: 19203
It is because you are defining a local variable currentRoom
that is specific to the method.
currentRoom = newRoom;
Is the correct syntax to accomplish a permanent change.
EDIT:
For clarification as to why your debugger showed you the wrong information:
It was showing you the contextual value that you selected. In this case currentRoom
meant something different inside MoveToANewRoom
so it "helpfully" update the value for you. As to whether there should be more clarification in cases like this has been subject to many debates :).
Upvotes: 5