I am new with C# and I can't understand why this code doesn't work.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
char[] sw = "ab".ToCharArray();
swap(sw[0], sw[1]);
string end = new string(sw);
Console.Write(end);
}
static void swap(char a, char b)
{
char temp = a;
a = b;
b = temp;
}
}
}
What I expect on console is "ba" but I get "ab". I was able to find different approach to solve this problem but what I would like to know is what is the mistake in this code. Thanks for the help!
The problem is that the swap
method is actually just manipulating local copies of a
and b
. You need to pass the arguments by reference. So you would define the swap
method like this:
static void swap(ref char a, ref char b)
{
char temp = a;
a = b;
b = temp;
}
And call it like this:
swap(ref sw[0], ref sw[1]);
It should be modified like the following (Note: in this example, ref char[] arr
is prefixed with ref
mostly for didactic purpose: array will be passed by ref
by default)
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
char[] sw = "ab".ToCharArray();
swap(0, 1, ref sw );
string end = new string(sw);
Console.Write(end);
}
static void swap(int indexA, int indexB, ref char[] arr)
{
char temp = arr[indexA];
arr[indexA] = arr[indexB];
arr[indexB] =temp;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With