-2
int a = 1;
int b = 7;
void SwapTwoIntegers(int a, int b)
{

    int temp = a;
    a = b;
    b = temp;

}
SwapTwoIntegers(a, b);
Console.WriteLine(a);

I was trying to write a function for swapping two variables, but it seems like i am going wrong somewhere in my code.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179

3 Answers3

2

The default for parameters is pass by value, which means you're only modifying a copy of a and b.

You'll want to pass the variables by reference, so that the originals can be modified.

void SwapTwoIntegers(ref int a, ref int b)

See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/method-parameters

nullforce
  • 1,051
  • 1
  • 8
  • 13
0

This is because you are passing a and b to the SwapTwoIntegers method by value, which means the method receives copies of the original variables. Any changes made to a and b inside the method only affect the copies, not the original variables.

To swap the values of a and b, you can modify the SwapTwoIntegers method to use ref parameters, like this:

void SwapTwoIntegers(ref int a, ref int b)
{
    int temp = a;
    a = b;
    b = temp;
}
Zeeshan
  • 484
  • 1
  • 5
  • 19
-1

you need to pass the values by reference, or either return the values from the SwapTwoIntegers function, something like

`public Tuple<int, int> SwapTwoIntegers(int a, int b)
{
int temp = a;
a = b;
b = temp;
return a, b;
}

a, b = SwapTwoIntegers(a, b);`

I think thats how you return two items in c#, or either learn about reference values https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref Hope it helps

San
  • 9
  • 3