1

Since passing a C# array as a function parameter is pass-by-reference, that means I can modify the array in the function. So here I am trying to allocate and modify the array in the function:

void caller() {
   int array[];
   doStuff(array);

   if (array != null) {
      // never reaches here, even when I allocated the array of size 0
   }
}

void doStuff(int[] array) {
   int[] tmp = new int[0];
   array = new int[tmp.Length];
}

Problem is that the array != null check never turns out to be true, even when I have allocated an array of size 0. I've confirmed in documents that new int[0] is a valid allocation command. What could I be doing wrong?

Taylor
  • 286
  • 4
  • 18
  • so what are you trying to reach? – Maytham Fahmi Jan 22 '19 at 20:53
  • It's *not* null, it's an empty array with length 0 that cannot be added to. Returning a zero-length array is just a way to get around a null check. See this answer: https://stackoverflow.com/a/4477470 – Adam V Jan 22 '19 at 20:53
  • Did you try specifying length more than 0 ? 0 would not allocate any space i guess. – Manoj Choudhari Jan 22 '19 at 20:53
  • 3
    "Since passing a C# array as a function parameter is pass-by-reference" No. Reference types / value types is a different concept than pass-by-reference / pass-by-value. You are passing `array` by value. Pass it by reference with the `ref` keyword. – Dennis_E Jan 22 '19 at 20:54
  • 1
    Possible duplicate of [What does int test\[\] = new int\[0\] mean?](https://stackoverflow.com/questions/4477460/what-does-int-test-new-int0-mean) – Adam V Jan 22 '19 at 20:55
  • 1
    Also, this does not compile. – Dennis_E Jan 22 '19 at 20:55

2 Answers2

3

That will never work, unless you pass by reference.

Your first variable is null, when you pass it along you pass along a reference (by value!) to nothing. Your method than assigns its copy of the reference to some other array. That won't affect the original variable.

If you want that to work, you have to actually pass by reference (using out or ref).

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
-1

since the array is initialized (with the new int command), it will never be null, just an declared empty space (with no data). You can check the length in the caller method, in the if.

StefanaB
  • 184
  • 2
  • 11