Reputation: 316
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?
Upvotes: 1
Views: 540
Reputation: 61369
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
).
Upvotes: 3
Reputation: 183
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.
Upvotes: -1