Will the discard variable _ call Dispose() when put in a using statement? [duplicate]
Asked Answered
A

1

1

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://mcmap.net/q/1285781/-c-7-0-discards-and-idisposable-out-argument, he says _ doesn't call dispose when used like this:

var a = TestMethod(out _.Dispose());
Abyssinia answered 26/4, 2021 at 23:5 Comment(2)
Did you try it and put a breakpoint to see if it would hit?Matrilateral
out _.Dispose() is invalid syntax. Dispose doesn't return a ref Disposable (and I'm not sure the language could use that if it did--but I haven't tried it). See this answer for a better way to dispose a disposable output parameter.Rawley
B
2

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.

Bipartite answered 26/4, 2021 at 23:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.