Is there a way to share variables or properties between two classes?
For example, I have a Blazor web app with 2 pages and 2 partial classes. How can I share the variable A from class 1 with class 2?
Is there a way to do this?
I would be very grateful for an answer.
CodePudding user response:
You could transfer the property through the parameter of the constructor.
So for instance you are in Form1 and want to transfer variable_A to Form2 then you simply put variable_A in the constructor of Form2.
The code in Form1:
private void GoToSecondForm_Click(object sender,eventarg e)
{
Form2 f = new Form2(variable_A);
this.Hide();
f.ShowDialog();
}
Code in the constructor of Form2:
{dataType} variable_A;
public Form2({dataType} variable_A)
{
InitailizedComponent();
this.variable_A = variable_A;
}
If you do this then you will be able to use a variable in another form.
CodePudding user response:
If you have a class with a member variable that you want to be accessed in another class, you will want to include accessor/mutator (getter/setter) methods in the first class. For example, if you had two classes A and B, and A had a variable x that you wanted to access, you would do something like this:
public class A {
private int _x = 0;
public int getX() {
return this._x;
}
public void setX(int x) {
this._x = x;
}
}
public class B {
A a = new A();
public int returnX() {
a.setX(8);
return a.getX();
}
}
The returnX function would return 8 in this case. If we didn't set _x to 8, it would return 0, as that is what _x is initialized to when new A() is called. You can make _x a public variable and access it by writing something like a._x in B, but this is generally considered bad practice.
