Variables declared and initialized in Main, are not able to be changed through methods belonging to
other classes. This is extremely unintuitive and there must be a way around this.
Anyone know why, and how to solve? Or am I not understanding something fundamental about inheritance.
TestClass stuff = new TestClass();
int test = 1;
Console.WriteLine("This is an integer: {0}\nAnd this is an amount it's added with: 2", test);
stuff.ChangeVariable(test);
Console.WriteLine("\nand it's {0} here! Why doesn't the change stick!?", test);
class TestClass
{
public void ChangeVariable(int item)
{
item += 2;your text
Console.WriteLine("\nFor some reason, 'item' here is {0},", item);
}
}
>Solution :
You are not understanding something fundamental.
Your code doesn’t use inheritance. Your code has two classes but they don’t inherit. You are using an implicit Main method that belongs to a class and you are defining a class named TestClass. These two classes have no relation to each other.
There are no global variables in C#. int test is a local variable in the implicit Main method.
int is a value type, not a reference type. When you pass test to the ChangeVariable() method, the value of test is passed but not a reference to the test variable. The changes made to item are limited to the ChangeVariable() method.