3

I am using a memory stream like this:

public static byte[] myMethod()
{
    using(MemoryStream stream = new MemoryStream())
    {
       //some processing here.
       return stream.toArray();
    }
}

I am assigning the returned byte array in the caller method like this:

public static void callerMethod()
{
    byte[] myData = myMethod();
   //Some processing on data array here
}

Is the returned byte array passed by reference or by value? If the returned array is by reference does that mean at any time I may have myData in the callerMethod array to be null at any time while I am still processing the data?

5
  • 1
    How should the byte array change 'while you are still processing'? If it isn't assigned yet, how can it change? Commented Mar 31, 2016 at 12:08
  • You asking if the array will be null after the stream is disposed? That won't happen. Commented Mar 31, 2016 at 12:09
  • It is assigned by calling myMethod(), I guess It will be changed if the byte array is returned by reference, because the memory stream object now will be a subject for GC any time after execution exits using block in the called method? Commented Mar 31, 2016 at 12:12
  • Thanks @Rinecamo, yeah that exactly what I am asking for. Commented Mar 31, 2016 at 12:13
  • ToArray() returns and a new array filled with the stream data, so you can dispose the stream safely without loosing your data array Commented Mar 31, 2016 at 12:15

2 Answers 2

4

Is the returned byte array passed by reference or by value?

An array is an instance of an Array class, so it is always a reference and no value. ToArray reads the values from the stream and stores them in a newly instantiated array object.

does that mean at any time I may have ... null

No. As explained above, you return a new array instance containing the values read from the stream. There is no chance that your local variable myData will be set to null again while you work with it.

Sign up to request clarification or add additional context in comments.

Comments

0

This will be a reference, but you data will be store somewhere in your memory. So When "myMethod" will return, stream will be closed but your array will still contain the data. The only way you array could be null would be that your stream doesn't contain any data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.