Nate
Nate

Reputation: 129

Changing variable values after method

thank you for helping with multiple coding issues in the past but I've stumbled onto one more. I really need some directions on this.

In the script below, I am trying to change the value of b when met1, met2 and met3 are called in the Main function.

    class Class3
{
    public class Storage
    {
        public static int a = 100;
        public static int b = a + 5;
    }
public static void Main()
    {
        Methods Test = new Methods();
        Console.WriteLine("Original a value: {0}", Storage.a);
        Console.WriteLine("b value: {0}", Storage.b);
        Test.Met1();
        Console.WriteLine("After met1: {0}", Storage.a);
        Console.WriteLine("b value: {0}", Storage.b);
        Test.Met2();
        Console.WriteLine("After met2: {0}", Storage.a);
        Console.WriteLine("b value: {0}", Storage.b);
        Test.Met3();
        Console.WriteLine("After met3: {0}", Storage.a);
        Console.WriteLine("b value: {0}", Storage.b);
    }
    public class Methods
    {
        public void Met1()
        {
            Storage.a -= 10;
        }
        public void Met2()
        {
            Storage.a -= 10;
        }
        public void Met3()
        {
            Console.WriteLine("{0}", Storage.a);
            Met1();
            Met2();
            if (Storage.a > 10)
            {
                Met3();
            }
        }
    }
}

From my code above, the value of b stays at 105 even though the value of a changes. From what I can tell from here, variable b was not called again to change its value.

Should I put variable b as a method and call it? This is just an example I did and I have over 50 formulas that require changes whenever one of the variables within the formula changes. I dont think creating 50 over methods is a good idea as there should be a better way of coding this.

Thank you!

Upvotes: 0

Views: 563

Answers (1)

Rain336
Rain336

Reputation: 1498

Fields don't change automatically. That means that b = a + 5 will set b to 105. To re-calculate the value of b every time, you can change it to a property like:

public static int b => a + 5;

This way every time you access b it calculates a + 5.

Upvotes: 3

Related Questions