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?
>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. Theref
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)
.