Search code examples
c#dispose

Will the discard variable _ call Dispose() when put in a using statement?


I want to create a ZipArchive file if it doesn't already exist. Then I want to open it for reading its information before I update it. So is this valid use of the discard variable _ and does it work as intended?

using (_ = ZipFile.Open(filename, ZipArchiveMode.Update)) { }

There is a similar question https://stackoverflow.com/a/53797089/2229933, he says _ doesn't call dispose when used like this:

var a = TestMethod(out _.Dispose());

Solution

  • It is called - check the decompiled code on sharplab (or write a simple test snippet). But if you don't need the variable you can just skip the discard completely and write:

    using (ZipFile.Open(filename, ZipArchiveMode.Update)) 
    { 
    
    }
    

    With the same effect.