tags:

views:

743

answers:

4

I recently ran across some 3rd party C# code which does the following:

public int RecvByteDataFromPrinter(ref byte[] byteData)
{
    byte[] recvdata = new byte[1024];

    ///...fills recvdata array...    

    byteData = recvdata;
    return SUCCESS;
}

What does the line "byteData = recvdata" actually do in this case?

It appears that the goal is to have byteData contain the contents of the recvdata array. However, I was under the impression that you would need to do an Array.Copy(...) operation in order for that to happen.

Is this actually modifying the byteData reference to point to the newly allocated array? If so, is that array guaranteed to stick around?

+6  A: 

Yes, because of ref - it does modify the reference passed. Stick around? you mean - not destroyed? Yes, it will not be GC'd because of a new reference. The old array (passed) might be GC'd though after this assignment if no more references...

Array.Copy will actually copy elements, then you don't need "ref", but this will be more time-consuming

badbadboy
A: 

The byteData reference will now be pointing at the recvdata array, giving it a root. It will "stick around" until all of its roots are gone (i.e. the called gets rid of the byteData object passed in) and it becomes a collection candidate. The original array object passed is is a candidate for collection as soon as the method returns.

ctacke
+1  A: 

That code will assign the recvdata array reference to the byteData array reference. .NET will keep track of the assignment under the covers in its garbage collection logic so that the byte array that was originally assigned to recvdata will not go away underneath of you as long as byteData is in scope.

Zach
+2  A: 

You guessed right, the assignment is modifying the byteData array reference to point to the newly allocated array (because of the 'ref' keyword). The callers of the function will "see" the contents of the recvData array (whatever was filled in there).

And yes, the array sticks around as long as there's one reference to it left (in this case, whatever array you passed along to this function).

Dan C.