test
is not derived from
Form1
, so it doesn't have access to
Form1
data - and even if it did, it wouldn't "know" which of potentially hundreds of
Form1
instances contained the right value of
y
.
Think about it: if you put your mobile in the glove box of your car, and then we go for a drive in my car, do you expect to be able to open the glove box in front of you and retrieve your mobile? Of course not - you know it is in the glove box of your car, not mine and that the two cars, and the two glove boxes are completely separate and do not share anything.
To access the glove box content you have to explicitly specify the car: my car, yoru care, this car, that car: you can access each glove box in turn.
It's the same with classes: to access a variable in Form1 you have to specify exactly which instance of the form class you are talking about. Inside the form class itself, that is done via an implicit or explicit use of
this
:
public Form1()
{
InitializeComponent();
y = 666;
}
(Implicit)
public Form1()
{
InitializeComponent();
this.y = 666;
}
(Explicit)
From outside the form class, you need to use an explicit reference to the actual instance of the form that you want to access.
And ... that's a bad idea in your case, because the
test
class should not know that the
Form1
class even exists, let alone what variables it contains - it if does then you "lock" the two classes together, and you can no longer make a change to either without considering the effects on the other (which may be breaking changes if
Form1
decides that y should be a display control instead of a simple variable).