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?
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