Home > database >  Is a MemoryStream passed as a parameter reused or is a new one created?
Is a MemoryStream passed as a parameter reused or is a new one created?

Time:12-14

I return a stream for a file I download from OneDrive. There are a few things I need to do to this file in memory before uploading back to onedrive. I have these items done as separate functions to keep the controllers code more compact. My issue is I am struggling how the MemoryStream object is used. I do not want to create duplicate memory streams but I also do not want to create a memory leak (if possible in asp.net core). My code is as follows:

public ActionResult FinalizeDoc()
{
    using (var memoryStream = await oneDrive.DriveItemDownloadAsync(SharedDriveID, OneDrivePath, "path"))
    {
        DeleteComments(memoryStream);
        AcceptTrackChanges(memoryStream);

        var UploadDoc = await oneDrive.UploadFileStreamAsync(SharedDriveID, memoryStream, fullPath, "replace");
    }
}

public void DeleteComments(MemoryStream memoryStream)
{
    using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(memoryStream, true))
    {
        //delete comment code

    }
}

public void AcceptTrackChanges(MemoryStream memoryStream)
{
    using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(memoryStream, true))
    {
        //accept changes code

    }
}

I am struggling on what passing an object like this as a parameter does. Does edits to that MemoryStream inside these other functions that pass it as a parameter keep this as a single object in memory or is it making copies and since I am not returning the edited copy then really this setup does nothing?

I was also thinking I may be better off passing WordProcessingDocument as the parameter but again I still running into this same issue in not understanding if this makes a copy or is still a single object in memory.

CodePudding user response:

MemoryStream is a class, and classes are reference types. If it doesn't tell you anything (as I can see) — there are two kinds of types in C#, value types (structures) and reference types (classes). When you pass a value type, a copy is created, and when you pass a reference type, no copy is created. In fact, when you pass a reference type, only a reference to the actual object is passed.

So your methods FinalizeDoc, DeleteComments and AcceptTrackChanges all have references to the same MemoryStream, which of course means: when one method makes changes to that stream, other methods can see that changes immediately, as they are actually working with the same stream.

Learn more here.

  • Related