0

I'm trying to make a swap operation. But when i tried to swap, it changes temp and the orginal array. The codes are here.

    private int[] currentNumbers;

    currentNumbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

    public int[] getNumbers()
    {
        return currentNumbers;
    }

    int[] temp;
    int[] ux = numbers.getNumbers();

    int i=1, j=2;

    temp = swap(i, j, ux);

    public int[] swap(int i,int j,int[] u) {
        int t = u[i];
        u[i] = u[j];
        u[j] = t;
        return u;
    }

That code blocks changed ux array as planned. But changed currentNumbers. I don't want swap in orginal array. What can i do about that? Any ideas?

helb
  • 7,609
  • 8
  • 36
  • 58
mgkrks
  • 31
  • 2
  • 10

3 Answers3

2

Expanding on what SLaks said, your .getNumbers() function isn't returning a copy of the array, it's returning a reference directly to currentNumbers. If you want to return a new copy every time and not modify currentNumbers, you should use Array.Copy.

int[] ux;
Array.Copy(numbers.getNumbers(), ux, numbers.getNumbers.Length)

There are probably more optimal ways to do this, but this will get you what you want!

CraigularB
  • 440
  • 4
  • 11
1

You should use clone method in getNumbers method. http://msdn.microsoft.com/en-us/library/system.array.clone%28v=vs.110%29.aspx

Leon Borko
  • 198
  • 2
  • 13
1

Your problem is that arrays in c# are passed by reference, so you need to copy that array in another one, apply changes to that array, and then return it.

Check this answer for more details Passing Arrays by Value and by Reference

Community
  • 1
  • 1
prole92
  • 56
  • 5
  • 2
    The array *reference* is passed *by value* - it's a minor distinction with different consequences. See http://msdn.microsoft.com/en-us/library/8b0bdca4.aspx – Preston Guillot Dec 08 '13 at 20:41