I can't adequately explain why Console.WriteLine(val.getSetNum) from static void Main(string[] args) returns 0.
I would have thought that after calc()had been called, int num would have been set? I know I can make calc() return the value of needed, but really, I just want to satisfactorily explain to myself the other. Intuitively it doesn't look quite right because it creates a different class instance...
The wider issue, is understanding the best way to store boolean control variables accessed by various classes... instead of making them all static. Any help appreciated.
public class Program
{
private class Values
{
private int num;
public int getSetNum {get; set;}
}
public int calc()
{
Values vals = new Values();
vals.getSetNum = 6;
Console.WriteLine(vals.getSetNum);
return vals.getSetNum;
}
static void Main(string[] args)
{
Program prog = new Program();
Values val = new Values();
prog.calc(); //Outputs 6
Console.WriteLine(val.getSetNum);//Outputs 0 - why?
Console.ReadKey();
}
}
You're creating two different instances of Values
- one inside Main
, which keeps its value of 0 for getSetNum
, and one inside Calc
, which is given a value of 6 for getSetNum
. They're entirely separate instances.
You could fix this by returning the Values
reference from calc
instead. For example:
// TODO: Change *all* the names to be meaningful and comply with conventions
public int calc()
{
Values vals = new Values();
vals.getSetNum = 6;
Console.WriteLine(vals.getSetNum);
return vals;
}
static void Main(string[] args)
{
Program prog = new Program();
Values val = prog.calc();
Console.WriteLine(val.getSetNum);
}
Next:
The wider issue, is understanding the best way to store boolean control variables accessed by various classes
Well you'd need instances which are referenced by all of those classes. Without more information, it's hard to recommend any particular course of action - but often this sort of thing is best handled with dependency injection. But don't think you need to put all of this shared information in a single class - you should keep it partitioned logically. (Again, it's hard to be more specific without a concrete example of what you're trying to do.)
See more on this question at Stackoverflow