- foo cannot use ref/out/% nor any additional parameters.
- the actual parameter of foo has to be Object^.
The caller could allocate the array and pass it in, and you could modify elements within the array - but this is just casting the array to Object and back again.
If you want to change the actual array - eg assign it to a new array of different length, without using ref
(%
in C++/CLI) or out
([Out]
in C++/CLI), you can't do it.
Here's why:
The .NET virtual machine works by pushing and popping things onto a stack. The way you pass parameters to functions works like this behind the scenes:
- You Push the parameters (in this case, a reference to the array) onto the stack.
- You Call the function
- The VM sets up for the method call by reading these values off the stack in the specified order, and assigning them to local variables in your function.
- The code inside the function runs.
If the caller doesn't put valid data on the stack before invoking the function, it crashes. If the caller puts data in the wrong order - it crashes. If anything is funny with the stack at all - it crashes.
Additionally, methods cannot modify things that are already on the stack. (If they did, they would corrupt the stack - it crashes), they can only push and pop new things on and off the stack.
This means 2 things:
In order to call the function, you have to put a reference to the array onto the stack. Therefore the caller has to allocate the array itself, or pass a null reference.
You can't change the reference to the array, so the function can't provide a new array. As arrays are inherently non-resizeable, this means that you can't add new elements (you can however change existing elements)
Disclaimer: Eric lippert is probably going to come and explain why everything I've just written is wrong, but to the best of my knowledge and research, that's how it works