-1
private void assign(int num)
{
   num = 10;
{

private void doSomething()
{
   num = 0;
   assign(num);
   MessageBox.Show(num.ToString());
}

I get the answer 0 and not 10. can someone explain how this happens? my objective is to modify the variable.

Pathum
  • 18
  • 3
  • 1
    2 options: pass your num as `ref`, or use a `return` value. Both are keywords, try msdn to see how they work – Stefan May 19 '18 at 10:46
  • https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/return – Stefan May 19 '18 at 10:46
  • https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref – Stefan May 19 '18 at 10:47
  • @xanatos: indeed... it must be otherwise this wouldn't compile... although the misplaced `{` is also an indication that this is not the actual code. – Stefan May 19 '18 at 10:52

1 Answers1

2

As from comments you have 2 options, ref and out

1)

private void assign(ref int num)
{
   num = 10;
}

private void doSomething()
{
   int num = 0;
   assign(ref num);
   MessageBox.Show(num.ToString());
}

2)

private int assign(out int num)
{
   num = 10;
}

private void doSomething()
{
   var num = 0;
   assign(out num);
   MessageBox.Show(num.ToString());
}

Normally this is done by returning the value:

private int assign(int input)
{
   //some complicated calculation on input.
   return 10;
}

private void doSomething()
{
   var num = 0;
   num = assign();
   MessageBox.Show(num.ToString());
}
Stefan
  • 17,448
  • 11
  • 60
  • 79
  • Thanks a lot Stefan...This worked. Actually I am returning a bool value depending on certain conditions in this method so I cannot return the integer value. Thanks for the help.. – Pathum May 19 '18 at 11:11