How is the byte array being filled with the text from the file

Hi I don’t fully understand how the byte array is being filled within the load method:

   public void Load(string saveFile)
        {
            string path = GetPathFromSaveFile(saveFile);

            print($"Loading from {GetPathFromSaveFile(saveFile)}");
            using (FileStream stream = File.Open(path, FileMode.Open))
            {
                byte[] byteBuffer = new byte[stream.Length] ;
                stream.Read(byteBuffer, 0, byteBuffer.Length);

               print(Encoding.UTF8.GetString(byteBuffer));
            }
        }

More specifically the lines:

byte[] byteBuffer = new byte[stream.Length] ;

From my understanding, the stream.length is setting the size of the array, but isn’t filling it with the bytes from the file, is it?

This is somehow happening on the next line:
stream.Read(byteBuffer, 0, byteBuffer.Length);

How is this happening, is it changing the array when it’s passed into the read method?

Yes, to put this is layman’s terms

byte[] byteBuffer = new byte[stream.Length];

creates a container large enough to hold all of the contents of the file.

stream.Read(byteBuffer, 0, byteBuffer.Length);

takes the reference to that container and fills the contents with the bytes from the stream.

When you pass an Array, List, Class, or Dictionary to a method, you’re actually passing a pointer to the object in question, not the actual object itself. (You would overflow the stack quickly if you passed the actual data structure in it’s entirety).

If Read did this:

void stream Read(byte[] byteBuffer, int startPos, int length)
{
    byteBuffer = new byte[length-startPos];
    //fill characters in byteBuffer
}

nothing would happen to the original byteBuffer, since the reference will have been overwritten in the method, but instead, Read simply fills the contents of the existing container byteBuffer. With reference values, you can alter the contents. You’re not actually changing the address of byteBuffer, only what’s held within it.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms