Reputation: 41
Other methods like Array.Sort() don't use ref
and yet they change the array.
Also this code confuses me:
using System.Linq;
using System;
namespace jmennyprostor {
public static void Main(string[] args)
{
int[] mojepole = {4,4,5,2,4};
pole.changearray(mojepole); // this does change mojepole
pole.resizearray(mojepole); // this magically does not change mojepole
pole.resizearrayworking(ref mojepole); // this DOES change mojepole
}
public class pole
{
public static void changearray(int[] polerole)
{
polerole[2] = 44444;
}
public static void resizearray(int[] polerole)
{
Array.Resize(polerole);
}
public static void resizearrayworking(ref int[] polerole)
{
Array.Resize(polerole);
}
}
}
Upvotes: 0
Views: 369
Reputation: 89361
Because the array may not actually be resized. So you pass in a reference to an array of size N, and the method may allocate a new array of size newSize
and change your reference to point to the new array.
It has a similar effect as
oldArray = Array.Resize(oldArray, newSize);
if the method returned a reference to the new array instead of using a ref argument.
Upvotes: 2