I got a question about variables in C#.
I am trying to save a variable in a different class. I use Add --> New Item --> Class (So it is a complete new class where I want to save my variables I need to use throughout my project). I use getters and setters to save them.
I call the class in Form1 by using: private GlobalVars globalVars = new GlobalVars();
Now when I press a button a new Form appears where I use the same statement else I can't access the class. But when
I try to access a variable by using e.g: globalVars.intClient.toString(); I always get 0. The variables have been reset.
How can I solve this problem ??
Loading
Jaish MathewsPosted May 2, 2010, 2:36 AM
With your code it is not possible because
{
private Class classe = new Class();
Above code meant that you are creating a copy of class named "Class" which can use only inside class "Form1". It's not accessible to any other class
{
private Class classe = new Class();
Above code meant that you are creating a copy of class named "Class" which can use only inside class "Form2". It's not accessible to any other class
So you have 2 copies of the class "Class", one inside "Form1" and another inside "Form2". The code "classe.intClient = 4" only applied to the copy of "Form1" not in side the copy of "Form2". So "Form2" can't access "classe.intClient = 4". If you need to access it globally, do like below.
Redefine "Class" LIke Below
class Class
{
public static int intClient
{
get;
set;
}
}
Set The Above Property Any Where Liek Below
Class.intClient = 4
RowiePosted May 2, 2010, 4:42 AM
I also had to change: classe.intClient = 4; to Class.intClient = 4;
Else I got an error.
RowiePosted May 1, 2010, 12:15 PM
I got 3 files:
- Form1.cs <-- Form
- Form2.cs <-- Form
- GlobalVars.cs <-- Class
Form1 looks like:
public partial class Form1 : Form
{
private Class classe = new Class();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
classe.intClient = 4;
Form2 form = new Form2();
form.Show();
}
}
Form2 looks like:
public partial class Form2 : Form
{
private Class classe = new Class();
public Form2()
{
InitializeComponent();
MessageBox.Show(classe.intClient.ToString());
}
}
Class.cs looks like:
class Class
{
public int intClient
{
get;
set;
}
}
Now when I press the button on form 1 I set a value in class.cs. The messagebox.show() gives 0 as output. I want it to output 4 since I have set that on Form1.
Mahesh ChandPosted May 1, 2010, 11:16 AM