0

This is messing with my mind, I've been trying to wrap my head around it for ages. I've been through a few questions on here and I still don't get it. I've visited Jon Skeet's page and etc. I tried writing my own code to see if I understood the concept but for the code below when I try to print out nums[0] it gives me 500, shouldn't it print out 1 since the array should have been passed by value because "C# passes by value by default" ?

UPDATE: aThing is just randomly changing an index to see if changes in r are reflected in nums

static void Main(string[] args)
    {
        int[] nums = new int[] { 1, 2, 3, 4 };

        aThing(nums);

        Console.WriteLine(nums[0]);
        Console.ReadLine();
    }

    static void aThing(int[] r)
    {
        r[0] = 500;
        r = null;
    }

Just for interest's sake, how would I modify r without modifying numbs ?

  • what are you trying to do inside aThing()? – Sajeetharan Jul 06 '14 at 15:16
  • 1
    Pass a copy of the array to *aThing*. For ex, `nums.ToArray()` – EZI Jul 06 '14 at 15:19
  • Just randomly changing an index to see if changes in r are reflected in nums – Question Mcquestioner Jul 06 '14 at 15:21
  • This got marked as a duplicate. Does the answers there answer your question? – Guffa Jul 06 '14 at 15:25
  • 2
    In C#, arguments can be passed to parameters either by value or by reference. Passing by reference enables function members, methods, properties, indexers, operators, and constructors to change the value of the parameters and have that change persist in the calling environment. To pass a parameter by reference, use the ref or out keyword. Reference types, and array is one such type, always pass a reference, but not by reference. So while you can safely change any of the array elements, changing the entire array by assigning a new one will not work. – Darek Jul 06 '14 at 15:26
  • 2
    Don't confuse passing by reference with reference types. nums is passed by value, which means it is a different variable than r, but both nums and r reference the same array. When you say r = null, r will then no longer reference that array, but nums will. If you had passed it by reference, nums would also be null, because r and nums would be the SAME variable. – Dennis_E Jul 06 '14 at 15:30

1 Answers1

0

By copying it.

A solution would be to call your method like this:

aThing(nums.ToArray()); // copy the array before passing it
Olivier
  • 5,578
  • 2
  • 31
  • 46