Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# passing int[] (array) with and without ref [duplicate]

I am slightly confused about this, as I have read that an int[] array, although int is a primitive type, since it's an array, it's a reference type variable.

What is the different then between a method such as:

public static void ChangeSomething(ref int[] array)
{
     array[0] = 100;
}

and

public static void ChangeSomething(int[] array)
{
     array[0] = 100;
}

When the array is modified, I can see the new value of 100 at index 0 for both of these calls.

Is there something different that happens under the covers which makes one better than another? Does the VS IDE allow both simply because perhaps the "ref" keyword clarifies the intention?

like image 266
blgrnboy Avatar asked Jun 02 '26 13:06

blgrnboy


2 Answers

The difference is that you can assign the original variable directly in the method. If you change your method to the this:

public static void ChangeSomething(ref int[] array)
{
     array = new int[2];
}

And call it like this:

var myArray = new int[10];
ChangeSomething(ref myArray);

Console.WriteLine(array.Length);

You will see that myArray only have a length of 2 after the call. Without the ref keyword you can only change the content of the array, since the array's reference is copied into the method.

like image 73
MAV Avatar answered Jun 04 '26 02:06

MAV


If you modify the items of the array, there is no difference.

But if you redefined the array itself with larger array, there is the difference:

public static void ChangeSomething(ref int[] array)
{
     array = new int[100]; //you are changing the variable of caller
}

and

public static void ChangeSomething(int[] array)
{
     array = new int[100]; //you are changing local copy of array variable, the caller array remains same.
}
like image 43
Tomas Kubes Avatar answered Jun 04 '26 02:06

Tomas Kubes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!