Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# global variables unchangeable outside of locality?

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.

Screenshot of code and result

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading