1seanr 1seanr - 1 month ago 6
C# Question

C# how to create an instance of a class in one function and then use that same instance in another function

This is probably a really short answer but I just don't know the syntax for it and cant find examples of it anywhere online that involve multiple instances of classes that depend on each other.


I have this but its not working because the instance of game cannot be found because it is in another function.


All of the resources I can find are on referencing strings and objects outside/between methods but this don't even know what to do because I have tried all of those ways that they said to do with objects and variables but I just cant get it going. Because when i do it those ways as shown buy creating it before hand it always clears game to null just before it enters the second function.

public void Go()
{
MockFiler Mock = new MockFiler("###\n# #\n#@#\n###");
Game game = new Game(Mock);
game.Load("h:\theFileNameDoesNotMatterAsItReturnsAString"); // All gets created fine and used fine

string Level = game.Level;
View.ShowGame(Level); // Some winforms code in here
}


// As soon as trigger is setoff in the winforms code it calls this function
// as soon as the attention point comes back in this class to here the game is == null
public void PassMove(Direction Direction)
{
game.Move(Direction); // so the instance of game becomes null and i cant call this function inside it
string Level = game.Level;
View.ShowGame(Level);
}


I have tried all of those things like calling Game outside of the first method and then setting it inside that first method but it always clears it. I think it is to do with the MockFiler not setting it properly or note being accessible or something little and silly.

Answer

You should create the instance globally for both Game and MockFiler , It will be outside of both functions,

 //Creating instance and passing 
 MockFiler Mock = new MockFiler("###\n# #\n#@#\n###"); 
 //Creating instance  for Game
 Game game = new Game(Mock);
 //Now these can be accessed anywhere within the methods 
 public void Go()
  {         
    game.Load("h:\theFileNameDoesNotMatterAsItReturnsAString");
    string Level = game.Level;
    View.ShowGame(Level); 
}    
public void PassMove(Direction Direction) 
{
    game.Move(Direction);  
    string Level = game.Level;
    View.ShowGame(Level);
}
Comments