long time reader, first time poster:
I've been trying to pick up C# and writing a game program, but am hung up on how to transfer data to my GUI from logic classes and visa-versa. Transferring strings would be ideal, and it seems pretty simple, so I was hoping someone could help me out.
In the most basic case, I'd like to know why this isnt working:
namespace MyGame
{
public partial class GameWindow : Form
{
public LogicClass gameLogic;
public GameWindow()
{
InitializeComponent();
}
private void startButton_Click(object sender, EventArgs e)
{
string toDisplay = gameLogic.getString();
this.label1.Text = toDisplay;
}
}
and the game logic class
namespace MyGame
{
public class LogicClass
{
public string getString()
{
return "success!";
}
}
}
I've tried for a few days now to find out why I get a nullReferenceException at line
string toDisplay = gameLogic.getString();
this isn't the end result of what I'd like to do, of course, but if somebody could explain to me what's going on here and how I could pass a string from a different class to the GUI I think I'll be able to get a foothold into how to do the rest of the things that I'd like. I've seen a lot of things on transferring data from forms to other forms, but I can't find what I need about classes to forms. I know it can be done; its just too simple not to be possible. Can anyone help me out?
Thanks! Jake
Your data transfer logic is fine, the reason for the exception is gameLogic is never instantiated. You could replace public LogicClass gameLogic;
with public LogicClass gameLogic = new LogicClass();
Or add gameLogic = new LogicClass();
in the constructor after the call to InitializeComponent().