Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function for swapping 2 elements in an array doesn't work

Tags:

c#

swap

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!

like image 298
user2373458 Avatar asked Dec 01 '22 21:12

user2373458


2 Answers

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]);
like image 66
James Holderness Avatar answered Dec 05 '22 17:12

James Holderness


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;
            }
        }
    }
like image 38
Alexander Bell Avatar answered Dec 05 '22 18:12

Alexander Bell