2

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?

blgrnboy
  • 4,877
  • 10
  • 43
  • 94

2 Answers2

7

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.

MAV
  • 7,260
  • 4
  • 30
  • 47
5

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.
}
Tomas Kubes
  • 23,880
  • 18
  • 111
  • 148