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);
}
}
CodePudding user response:
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.
CodePudding user response:
If you don't use the ref
keyword, it won't change the variable in the other class.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref
So if you want it to change the variable, your code should look like this:
using System;
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(ref test);
Console.WriteLine("\nand it's {0} here! Why doesn't the change stick!?", test);
class TestClass
{
public void ChangeVariable(ref int item)
{
item = 2;
Console.WriteLine("\nFor some reason, 'item' here is {0},", item);
}
}