Reputation: 173
I'm a beginner with C# and I think there is something fundamental about instantiation and passing references that I just do not get.
I am trying to get the default Program class to instantiate 2 other classes, a form called frmGameUI and a class called LocHandler. If this was working correctly the LocHandler would then check the current location and assign the text properties of frmGameUI. For some reason the method to set the properties in LocHandler can not see or get my reference to frmGameUI that I instantiated in Program. What am I doing wrong?
static class Program
{
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainUI());
GameUI frmGameUI = new GameUI();
frmGameUI.Show();
LocationHandler LocHandler = new LocationHandler();
LocHandler.InitializeRoom();
}
And here is the LocHandler class:
class LocationHandler
{
private string currentRoom = "LivingRoom";
public void InitializeRoom()
{
if (currentRoom == "LivingRoom")
{
frmGameUI.btnLocation1.Text = "Bedroom";
frmGameUI.btnLocation2.Text = "Kitchen";
frmGameUI.btnLocation3.Text = "Patio";
}
}
}
in LocHandler, VS is telling me that frmGameUI does not exist in this context. I'm sure there is something fundamental and simple I just don't grasp here. Any help is appreciated!
Upvotes: 0
Views: 993
Reputation: 4733
Create different class with initialized instances and keep them there as public's
Upvotes: 0
Reputation: 23796
Yes, you're definitely missing some fundamental concepts. In C# variables aren't global. They have scope, see: http://msdn.microsoft.com/en-us/library/aa691132(v=vs.71).aspx. In your case, the scope of GameUI frmGameUI = new GameUI();
is local to the the method that you declared it in. So, nobody outside of that method can see that variable. That is to say, they can't see the variable by that name. That's NOT to say that you can't pass that variable to another method. So, if you need the LocationHandler
class to deal with that variable, then perhaps you should pass it to the InitializeRoom method. Like this:
LocHandler.InitializeRoom(frmGameUI);
Note that your method signature would change to:
public void InitializeRoom(GameUI gameui)
and then your code in that method would refer to the gameui
variable.
///<snip>
gameui.btnLocation1.Text = "Bedroom";
gameui.btnLocation2.Text = "Kitchen";
gameui.btnLocation3.Text = "Patio";
Make sense?
Upvotes: 3
Reputation: 1714
Execution of the Main
method will stop on this line, while the main form is showing.
Application.Run(new MainUI());
So what you probably want to do is move the code to create LocationHandler
above this line, and pass it in to GameUI
. (and also replace MainUI
with GameUI
)
Upvotes: 0