views:

50

answers:

2

Hi there,

here is the situation: I want to call a method from a C++ module, and pass an array to it:

x.Method(array, ...)

x is a C# object. I would suppose that I could change the array and fill it with my own data - but it seems not be the case (?)

How should I pass the array by reference and change its content in the method?

Thank you in advance,

cheers.

+1  A: 

You don't need to pass the array by reference. Array is a reference type, so if you pass the array to the method, you're actually passing a reference to it. The method can change the content of the array pointed by the reference, but cannot change the reference itself (i.e. it can't make it point to a different array). If you were passing the array by reference, the method would be able to change the reference to the array, but that's probably not what you're looking for if you just want to fill an existing array.

I suggest you have a look at this article for more details

Thomas Levesque
+1  A: 

Yes, if you want to alter the array beyond just altering its elements (i.e. adding or removing elements) then you have to pass it by reference. The C# declaration would be:

 public void Method(ref Mumble[] arg)

Which isn't great syntax. The garbage collector makes it easy to return an array as the function return value:

 public Mumble[] Method(Mumble[] input)

But consider a List<Mumble> instead.

Hans Passant