tags:

views:

202

answers:

4
+5  Q: 

basic c# question

why doesn't the element get swapped

public static void SwapArray(int[,] arr)
    {
        for (int i = 0; i < arr.GetLength(0); i++)
        {
            for (int j = 0; j < arr.GetLength(0); j++)
            {
                int temp = arr[i, j];
                arr[i, j] = arr[j, i];
                arr[j, i] = temp;
            }
        }
    }

even if the parameter is without a ref modifier the array doesn't change. a copy of the reference is passed as a parameter right?

+1  A: 

a copy of the reference is passed as a parameter right?

Arrays are passed by reference.

SwapArray(ref int[,] arr)

Here you are passing a reference by reference (sorry, for tautology), this means, that you can even reassign a reference:

arr = new int [10,20];
n535
+4  A: 

The second arr.GetLength(0) should be arr.GetLength(1). Because you want to use the 2nd dimension.

CSmooth.net
No, in the line `arr[i, j] = arr[j, i];` an `int` is copied by value. But you spotted the real problem in the next sentence. (+1)
Henk Holterman
+20  A: 

There is an error in your algorithm. For every i and j, your loop swaps arr[i,j] and arr[j,i] twice.

For example arr[3,1] gets swapped with arr[1,3] once for i=3, j=1 and once for i=1, j=3. So the result is the original matrix. You should change the j-loop to

for (int j = 0; j < i; j++) 
Jens
This is the correct answer to the question. Another thing to note is that this will only "work" if the array is square. If i != j then it will try to assign to parts of the array that do not exist.
ck
Basic problem is in your loop not in the C# ref and value type passed parameter, change your algo as mentioned by Jens A, and see that is the output.
Asim Sajjad
+1  A: 

try this.

I have changed the second for loop. u r actually swapping and again reswapping. so u stand where u were.

public static void SwapArray(int[,] arr) 
    { 
        for (int i = 0; i < arr.GetLength(0); i++) 
        { 
            for (int j = i+1; j < arr.GetLength(0); j++) 
            { 
                  int temp = arr[i, j]; 
                  arr[i, j] = arr[j, i]; 
                  arr[j, i] = temp; 
             } 
        } 
    } 
isthatacode
Nitpicking: The inner loop should start at i+1, not i. What's the point of swapping arr[i,j] and arr[j,i] if i==j?
nikie
correct i added a check for i!=j. But what u say is correct. Changed it now. thank u!!!!
isthatacode