How would I use a variable declared in Program.cs and access it’s value from Form1.cs?
I know how to do this in C, but I’m completely lost in Microsoft’s little twist on C.
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using LuaInterface;
namespace WindowsFormsApplication1
{
static class Program
{
public static Lua lua = null;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
lua = new Lua();
}
}
}
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LuaInterface;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
lua.DoString("print('hi')");
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = "";
}
}
}
Using your examples of
Program.csandForm1.csand assuming these are the default names and that you have aProgramclass that instantiates aForm1class and that you want to pass a parameter to theForm1class, you can do the following:Define a constructor for
Form1that takes this parameter and chain to the default constructor:In your
Programclass when instantiatingForm1, pass the parameter to it:Note that I am using OOP terminology – objects and classes (not files).
Update:
Since you have declared your
luavariable as a public static member of theProgramclass, you can access it anywhere in your program (assuming the namespaces have been declared appropriately) as follows:Though you would want to instantiate the static field before calling
Application.Run.In any way, this makes the object a public shared resource across all threads – making it virtually untestable and difficult to work with if you go multi-threaded.