I have a variable that I’m trying to set with Class1.SetVariable(variable); but it won’t return the variable I set it to. The variable will equal 0 in the other function in Class2, not the 50 that I want. Any ideas? Code:
Updated:
class Class1 {
public int rndk = 0;
public int Rndk {
get { return this.rndk; }
set { this.rndk = value; }
}
}
class Class2 {
public Class1 instance = new Class1();
public Class2() {
Load();
Check();
}
public void Load() {
instance.Rndk = 50;
Console.WriteLine(instance.Rndk);
// returns 50
}
public void Check() {
Console.WriteLine(instance.Rndk);
// returns 0
}
}
That’s pretty much the code.
First off, in C#, it’s typically better to make this a Property instead of a field with a “set method”:
This is essentially two methods, but wrapped in much nicer syntax.
As for the actual issue, I suspect the problem is that your methods aren’t working on the same instance of the
Class1class. Make sure you’re using the same instance in yourClass1variable, and not creating a new instance each method call. (Your existing code doesn’t demonstrate the actual problem.)For example, with the above change, this will work: