Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When editing an array "in place", why does overwriting the array not work, but overwritting each element does?

In C#, I have a function that should edit an array (not return new one). Why when I try to set the input variable to a new/update array it doesn’t work, but when I loop over the array and change all the values it does? I’ve been developing for some time and this has always been a thing I’ve just accepted, but was hoping someone could clear it up for me.

public static void RightCircularRotation(int[] input){
  var newList = new List<int>();
  newList.Add (input[input.Length-1]);

    for(var i = 0; i< input.Length-1; i++){
        newList.Add(input[i]);
    }
    // Why doesn't this overwrite the input variable, but the for loop does?
    //input = newList.ToArray();

    for(var i = 0; i< input.Length; i++){
        input[i] = newList.ElementAt(i);
    }
    
}  

I’ve tried to overwrite an input array with a new array but setting it to the new array with no luck. However, when I loop through and set each variable it does what I expect. Why is this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

int[] is a reference type and input is just a local variable storing that reference, so the first snippet just writes a reference to a new array (the result of ToArray call) into the local variable, while the second snippet updates the data stored by the "original" passed reference.

You can use ref keyword to make the first snippet work (though I’m not saying you should):

When used in a method’s parameter list, the ref keyword indicates that an argument is passed by reference, not by value. The ref keyword makes the formal parameter an alias for the argument, which must be a variable. In other words, any operation on the parameter is made on the argument.

public static void RightCircularRotation(ref int[] input)
{
    var newList = new List<int>();
    newList.Add (input[input.Length-1]);

    for(var i = 0; i< input.Length-1; i++){
        newList.Add(input[i]);
    }
    input = newList.ToArray();
}  

But this will require updating usages with it too – RightCircularRotation(ref someArray).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading