First off, in C#, it’s typically better to make this a Property instead of a field with a “set method”:
private int variable = 0;
public int Variable
{
get { return this.variable; }
set { this.variable = value; }
}
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 Class1
class. Make sure you’re using the same instance in your Class1
variable, 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:
public class Class2
{
private Class1 instance1 = new Class1();
public Class2()
{
instance1.Variable = 50;
}
public void Print()
{
// Using the same instance - will print 50
Console.WriteLine("Instance value is {0}", instance1.Variable);
}
5
solved C# – variable not setting from another class