Search code examples
c#arraysstreamdisposememorystream

C# - Effect of returning byte array of memory stream just before disposing stream?


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?


Solution

  • 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.