0

Here is the block of code that I am having a bit of trouble with:

using System;
namespace TestProgram {
    class Test {
        static void Main() {
            int number = 10;
            MultiplyByTen(number);
            Console.WriteLine(number);
            Console.ReadKey(true);
        }
        static public void MultiplyByTen(int num) {
            num *= 10;
        }
    }
}

When I run this block of code, I got 10 as the output instead of 100. My question is: Why does this happen and how to solve it? Thanks for the help.

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
Pixelbyte
  • 11
  • 2
  • Why would you think MultiplyByTen affects `number`? It saves the value to `num`. Your code contains no assignment to `number` other than the initializer. – John Wu Dec 01 '17 at 03:32
  • See https://meta.stackoverflow.com/questions/311829/why-cant-i-mark-my-title-as-solved – Peter Duniho Dec 02 '17 at 01:07

3 Answers3

3

The problem is that when the variable number enters into the method MultiplyByTen the value is copied and the variable you are modifying inside it's in fact the copy, so, the original was not changed.
Try this instead:

 public static void MultiplyByTen(ref int num) 
 {
     num *= 10;
 }

But remember you will have to call it with the ref keyword as well.

static void Main() 
{
    int number = 10;
    MultiplyByTen(ref number);//Notice the ref keyword here
    Console.WriteLine(number);
    Console.ReadKey(true);
}

I recommend you to also check this out: Passing Objects By Reference or Value in C#

Raudel Ravelo
  • 648
  • 2
  • 6
  • 24
1

You need to return the value back to the function also assign the returned value to the number.

  static void Main()
    {
        int number = 10;
        number = MultiplyByTen(number);
        Console.WriteLine(number);
        Console.ReadKey(true);
    }
    static public int MultiplyByTen(int num)
    {
        return num *= 10;
    }
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
1

Using your implementation:

using System;
namespace TestProgram {
    class Test {
        static void Main() {
            int number = 10;
            //MultiplyByTen(number);
            //Console.WriteLine(number);
            Console.WriteLine(MultiplyByTen(number));
            Console.ReadKey(true);
        }
        static public int MultiplyByTen(int num) {
            return num *= 10;
        }
    }
}
DevOpsSauce
  • 1,319
  • 1
  • 20
  • 52