-2

I don't know how function in Visual Studio C# work. My variable just change value in the function but after that it goes back to old value. I don't know why.

static void Plus(int a, int n)
    {
        for(int i = 0; i < n; i++)
        {
            a = a + 1;
        }
    }
    static void Main(string[] args)
    {
        Console.WriteLine("a = "); 
        int a = int.Parse(Console.ReadLine());
        Console.WriteLine("n = ");
        int n = int.Parse(Console.ReadLine());
        Plus(a, n);
        Console.WriteLine($"after plus a = {a}");
    }
WisdomSeeker
  • 854
  • 6
  • 8

1 Answers1

0

If you want to change a not its local copy, declare a as ref:

    // note "ref int", not just "int"
    static void Plus(ref int a, int n)
    {
        for(int i = 0; i < n; i++)
        {
            a = a + 1;
        }
    }

    static void Main(string[] args)
    {
        Console.WriteLine("a = "); 
        int a = int.Parse(Console.ReadLine());
        Console.WriteLine("n = ");
        int n = int.Parse(Console.ReadLine());
        Plus(ref a, n); // when calling we use "ref" as well 
        Console.WriteLine($"after plus a = {a}");
    }

A better (here: more readable) way, is to return the result:

    // we just return the result (note int instead of void) 
    static int Plus(int a, int n)
    {
        for(int i = 0; i < n; i++)
        {
            a = a + 1;
        }

        return a;
    }

    static void Main(string[] args)
    {
        Console.WriteLine("a = "); 
        int a = int.Parse(Console.ReadLine());
        Console.WriteLine("n = ");
        int n = int.Parse(Console.ReadLine());
        a = Plus(a, n); // we assign result to a
        Console.WriteLine($"after plus a = {a}");
    }
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215