Search code examples
c#disposeusingusing-statement

When there are multi using statement, will they be execute in order?


for example

  using (Stream ftpStream = ftpResponse.GetResponseStream())       // a             
  using (FileStream localFileStream = (new FileInfo(localFilePath)).Create()) // b
  {
                 ........do something
  }

will the two statement a and b executed in the order i put? and displose in the same order as well??

Thanks


Solution

  • They will execute in textual order, and be disposed in reverse order - so localFileSream will be disposed first, then ftpStream.

    Basically your code is equivalent to:

    using (Stream ftpStream = ...)
    {
        using (FileStream localFileStream = ...)
        {
            // localFileStream will be disposed when leaving this block
        }
        // ftpStream will be disposed when leaving this block
    }
    

    It goes further than that though. Your code is also equivalent (leaving aside the different type of localFileStream) to this:

    using (Stream ftpStream = ..., localFileStream = ...)
    {
        ...
    }