C
C#2y ago
rallez

Function that swap two numbers

Hi i need a function that swap 2 numbers I have written code below but it seems to doesn't work. Where am I wrong?
(int, int) Swap(int first, int second)
{
int temp = first;
first = second;
second = temp;
return (first, second);
}

int a = 5;
int b = 10;

Console.WriteLine(a);
Console.WriteLine(b);
Swap(a, b);
Console.WriteLine(a);
Console.WriteLine(b);
(int, int) Swap(int first, int second)
{
int temp = first;
first = second;
second = temp;
return (first, second);
}

int a = 5;
int b = 10;

Console.WriteLine(a);
Console.WriteLine(b);
Swap(a, b);
Console.WriteLine(a);
Console.WriteLine(b);
11 Replies
TheRanger
TheRanger2y ago
you never used what the method returned
Thinker
Thinker2y ago
Swap returns a new tuple, it doesn't modify a nor b a and b will always be 5 and 10 respectively.
Aaron
Aaron2y ago
I wouldn't even make a function for this
TheRanger
TheRanger2y ago
yeah (b, a) = (a,b)
MODiX
MODiX2y ago
Windows10CE#8553
REPL Result: Success
int a = 3;
int b = 5;
Console.WriteLine(a);
Console.WriteLine(b);
(a, b) = (b, a);
Console.WriteLine(a);
Console.WriteLine(b);
int a = 3;
int b = 5;
Console.WriteLine(a);
Console.WriteLine(b);
(a, b) = (b, a);
Console.WriteLine(a);
Console.WriteLine(b);
Console Output
3
5
5
3
3
5
5
3
Compile: 584.628ms | Execution: 36.117ms | React with ❌ to remove this embed.
rallez
rallezOP2y ago
ohh okay so i can do it that way will it also works with arrays? to swap for example 1st elemant of array with 2nd
TheRanger
TheRanger2y ago
alternatively u can do this
MODiX
MODiX2y ago
TheRanger#3357
REPL Result: Success
void Swap(ref int first, ref int second)
{
int temp = first;
first = second;
second = temp;
}

int a = 5;
int b = 10;

Console.WriteLine(a);
Console.WriteLine(b);
Swap(ref a, ref b);
Console.WriteLine(a);
Console.WriteLine(b);
void Swap(ref int first, ref int second)
{
int temp = first;
first = second;
second = temp;
}

int a = 5;
int b = 10;

Console.WriteLine(a);
Console.WriteLine(b);
Swap(ref a, ref b);
Console.WriteLine(a);
Console.WriteLine(b);
Console Output
5
10
10
5
5
10
10
5
Compile: 548.674ms | Execution: 33.201ms | React with ❌ to remove this embed.
MODiX
MODiX2y ago
Windows10CE#8553
REPL Result: Success
int[] arr = new int[] { 3, 5 };
Console.WriteLine(arr[0]);
Console.WriteLine(arr[1]);
(arr[0], arr[1]) = (arr[1], arr[0]);
Console.WriteLine(arr[0]);
Console.WriteLine(arr[1]);
int[] arr = new int[] { 3, 5 };
Console.WriteLine(arr[0]);
Console.WriteLine(arr[1]);
(arr[0], arr[1]) = (arr[1], arr[0]);
Console.WriteLine(arr[0]);
Console.WriteLine(arr[1]);
Console Output
3
5
5
3
3
5
5
3
Compile: 612.441ms | Execution: 40.498ms | React with ❌ to remove this embed.
Aaron
Aaron2y ago
yes, it does
rallez
rallezOP2y ago
okay so it's that easy great thanks you guys! ❤️
Want results from more Discord servers?
Add your server